![](/img/trans.png)
[英]jQuery UI: How can I have more than one "selectable" element if the element has to have id="selectable"?
[英]jQuery Selector: how can I specify one select menu when I have more than one?
我有4個選擇菜單,都有相同的產品。 (用戶應該使用選擇菜單將產品添加到發票中)。
因此,每個部分都由選擇菜單,數量文本字段和價格文本字段組成。 但我在同一頁面中有四個。
每當我從選擇菜單中選擇產品時,我想更改數量和價格。 但更具體地說,我想知道,如何找出點擊了哪個選擇菜單。
如果選擇菜單有一類產品(.product),當我選擇產品時,所有部分都會受到影響。 但我只想影響特定的選擇菜單部分。
$(".product").change(function(event){
alert('product picked'); // testing
});
我不能只是附加一個數字,如:product1,product2,product3。 因為那時在javascript文件中我將不得不寫出4種不同的功能
$(".product1").change(function(event){,
$(".product2").change(function(event){, etc.
我知道這是非常基本的,但我需要刷新我的jQuery東西。
這是HTML的一些形式。 我只包括產品選擇菜單和數量文本字段以簡化。
<div class="item">
<p>
Product:
<select class="product" id="invoice_line_items_attributes_0_item_id" name="invoice[line_items_attributes][0][item_id]"><option value="1" data-defaultquantity="1">WP setup</option>
<option value="2" data-defaultquantity="1">WordPress Theme Design</option>
<option value="3" data-defaultquantity="1">WHE/yr</option>
<option value="4" data-defaultquantity="1">WHE/mo</option></select>
</p>
Qty: <input class="quantity" id="invoice_line_items_attributes_0_quantity" name="invoice[line_items_attributes][0][quantity]" size="30" type="text" value="1"><br>
</div><hr>
<div class="item">
<p>
Product:
<select class="product" id="invoice_line_items_attributes_1_item_id" name="invoice[line_items_attributes][1][item_id]"><option value="1" data-defaultquantity="1">WP setup</option>
<option value="2" data-defaultquantity="1">WordPress Theme Design</option>
<option value="3" data-defaultquantity="1">WHE/yr</option>
<option value="4" data-defaultquantity="1">WHE/mo</option></select>
</p>
Qty: <input class="quantity" id="invoice_line_items_attributes_1_quantity" name="invoice[line_items_attributes][1][quantity]" size="30" type="text" value="1"><br>
</div><hr>
在您的事件處理程序中, this
將綁定到相關的<select>
元素。
$(".product").change(function(event){
alert($(this).attr('name')); // name of <select> element changed
});
一個方便的技巧是使用“數據”屬性將<select>
的內容與其他字段相關聯。 也就是說,你可以做一些事情,比如在數據屬性中存儲相關字段的“id”,以便處理程序可以找到要弄亂的字段:
<select name='whatever' data-quantity-id="whatever" data-price-id="whatever">
<option ... >
</select>
然后在處理程序中:
$('.product').change(function(event) {
var $quantity = $('#' + $(this).data('quantityId'));
var $price = $('#' + $(this).data('priceId'));
// ...
});
$(".product").change(function(event){
$(this).closest(".section").find(".quantity").val("somevalue");
$(this).closest(".section").find(".price").val("somevalue");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.