2017-05-19 4 views
1

私はjs(およびノー​​ドjs)を表現する初心者です。私は動的に作成されたボタンにonclickリスナーを実装しようとしています。ここ は私のコードノードjsで動的に作成されたボタンのボタンアクションを取得する方法は?

var express = require('express'); 
var app = express({mergeParams: true}); 

var products = [ 
    { 
     place1:[ 
      {id: 1, name: "choc1", price: 20}, 
      {id: 2, name: "choc2", price: 30} 
     ], 
     place2:[ 
      {id: 1, name: "coffee", price: 50} 
     ], 
     place3: [ 
      {id: 1, name: "oil1", price: 10}, 
      {id: 2, name: "oil2", price: 60}, 
      {id: 3, name: "oil3", price: 70} 
     ] 
    } 
]; 

app.get('/:place/:id([0-9]{1,})', function(req, res){ 
    if (products[0][req.params.place] === undefined) 
     res.send("place doesnt exist"); 
    else { 
     if (products[0][req.params.place][req.params.id - 1] === undefined) 
      res.send ("id doesnt exist"); 
     else { 
      console.log(products[0][req.params.place][req.params.id-1]); 
      res.render('small_div.pug', {product_name:products[0][req.params.place][req.params.id-1]}); 
     } 
    } 
}); 

app.get('/:place', function (req, res) { 
    res.render('native.pug', {product_name:products[0][req.params.place]}); 
}); 

module.exports = app; 
index.js

Native.pug

doctype html 
html 
    head 
     title="div dude" 
    body 
     div.main#main(style="height:300px;width:800px;border-style: solid;border-color: #ff0000 #0000ff;padding:10px") 
      each prod in product_name 
       // 
        Created by krishna on 19/5/17. 
       div.child1#child1(style="float:left;height:280px;width:30%;border-style: solid;border-color: #ff0000 #0000ff;margin:10px") 
        p.greetings#people1 Hello World! 
        p.id#id #{prod.id} 
        p.name#name #{prod.name} 
        p.price#price #{prod.price} 
        button.send#send(onclick='senddata()') Add to Cart 

script(src='/javascripts/try.js') 

try.js

function senddata() { 
    document.getElementById("send").innerHTML = "YOU CLICKED ME!"; 
} 

です

ボタンをクリックすると、最初のボタンだけが機能します。残りの部分は機能しません。エラーも表示されません。

助けてください。

ありがとうございました。

答えて

1

最後にわかりました。

ちょうど私がjavascriptでgetElementByIdをしようとすると、id 'send'の最初の要素だけが検索されました。すべての要素が動的に作成されたため、すべてがidを送信しました。

私はidを一意の{prod.id}に変更した後、それをonClickの関数に渡しました。問題が解決しました。

関連する問題