繁体   English   中英

如何在更改时更改克隆元素的值

[英]How do i change the values of cloned elements on change

我将onchange函数设置为表行中的select输入,我克隆并附加了onclick按钮的行。 克隆不响应所设置的onchange函数。 到目前为止的代码

 <!-- clone and append function--> $("button").click(function() { var clone = $('#item_row').clone(); $('#item_row').after(clone) }); $('#quantity').change(function() { $('.price').text($('.price').val() * $(this).val()) }) 
 <html> <body> <table> <thead> <tr id="item_row"> <td> <select id="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> </td> </tr> <tr> <td> <p class="price">20,000</p> </td> </tr> </thead> </table> <button>Fetch Row</button> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </html> <!-- begin snippet: js hide: false console: true babel: false --> 

有几个问题。

第一次使用.on如

$(document).on('click', '. quantity', function () {
    // do stuff here
});

其次,由于没有唯一标识符,js如何知道您要更改的数量? 您必须使用rel =“ unique_id”添加一个,并不断进行计数以添加到克隆的行中。

第三,不要使用ID =“ quantity”使其成为一个类,因为您将拥有多个

你去了:

您的数量计算错误, <p>没有“值”。 还对克隆的选择使用事件委托,否则它们将不会被识别。

 $("button").click(function(){ var clone = $('#item_row').clone(); $('#item_row').after(clone) }); $(document).on('change', '.quantity', function() { $('.price').text(parseInt($('.price').text()) * $(this).val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr id="item_row"> <td> <select class="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> </td> </tr> <tr> <td> <p class="price">20,000</p> </td> </tr> </thead> </table> <button>Fetch Row</button> 

更改更改事件的选择器,请使用class而不是id更改。Id对于整个文档是唯一的。对于动态创建的元素,请单击on()

 $("button").click(function() { var clone = $('#item_row').clone(); $('#item_row').after(clone) }); $(document).on('change','.quantity',function() { $('.price').text($('.price').val() * $(this).val()) console.log('changed') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr id="item_row"> <td> <select id="quantity" class="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> </td> </tr> <tr> <td> <p class="price">20,000</p> </td> </tr> </thead> </table> <button>Fetch Row</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM