簡體   English   中英

如何在javascript中匹配ID以在html上動態添加字段?

[英]How to match id in javascript for dynamically added field on html?

在我們的rails應用程序中,可以將動態字段添加到表單中。 這是動態添加的字段order_order_items_attributes_1413563163040_unit_price的html源代碼:

<div class="input decimal required order_order_items_unit_price">
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">
<abbr title="required">*</abbr>
Unit Price($)
</label>
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]">
</div>

如您所見,字段的ID中有13位數字的字符串,添加字段時會隨機生成。 我們如何在javascript中匹配(定位)這種類型的隨機ID? rails應用程序使用jquery(例如, $('#order_order_items_attributes_xxxxxxxxxxxxx_unit_price').change(function (){}) )。

我們是這種ID匹配的CSS類型的新手。 更多細節將不勝感激。

你有沒有嘗試過

$("input").prop("id");

這將搜索您的輸入字段並找到id屬性。

使用<label>for屬性:

var selector = $('.decimal.required.control-label').eq(0).attr('for'),
    element = $('#'+selector);

console.log(element);
// [<input id="order_order_items_attributes_1413563163040_unit_price" ... >]

您可以使用[attr*=value]使用屬性選擇器來匹配“包含”指定值的id。 喜歡:

$("[id*='order_supplier_id']").change(function() {

});

MDN關於屬性選擇器的文檔指定了可用於匹配屬性的選擇器類型,其中包括:

[ATTR * =值]
表示一個屬性名稱為attr且其值包含至少一個出現的字符串“ value”作為子字符串的元素。

您必須首先確定要使用哪種算法來匹配ID值。 根據您的意見(它不是在你的問題precistly指定),看來要找到以啟動所有ID "order_order_items_attributes_"和結束"_unit_price" ,並有它們之間的數字序列。

您可以這樣查找所有以您想要的事物開頭的id,然后將其過濾為僅符合所有三個條件的事物:

// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_supplier_id_\d+_unit_price$/;
$("[id^='order_supplier_id_']").filter(function(index) {
    return orderItemRegex.test(this.id);
}).change(function() {
    // this will be only the ids that match
});

它使用jQuery列出所有ID以"order_supplier_id_"開頭的對象的列表。 然后,它會過濾該列表,以消除與定義您的模式的完整正則表達式/^order_supplier_id_\\d+_unit_price$/不匹配的所有對象,然后將.change()事件處理程序僅掛接通過正則表達式測試的對象。

您可以維護一個元素ID數組,該元素ID數組在每次添加表單元素時都會更新。 然后,對數組中的元素調用change方法。 但是,如果更改事件回調對於所有新元素都相同,則不必這樣做。 只需在課堂上稱呼它即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM