簡體   English   中英

jQuery:如何訪問元素的名稱

[英]jQuery : how to access the name of the element

請參閱以下HTML代碼

<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

和jQuery代碼

$( "input[id*='product']" ).val( 'test' );

結果將默認顯示4個帶有'test'值的文本框,但是現在我喜歡顯示4個帶有產品名稱值的文本框,這意味着第一個文本框將顯示'Samsung',第二個文本框將顯示'Apple'等上,那么我應該在jquery代碼中輸入什么命令? 請建議。

只需使用.val(fn)

 $("input[id^='product_']").val(function() { return this.name; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="product_code1" name="Samsung"><br> <input id="product_code2" name="Apple"><br> <input id="product_code3" name="Huawei"><br> <input id="product_code4" name="Motorola"><br> 

對於每個輸入元素,它將調用該函數,該函數將返回要設置的值。

獎金

為了更加簡潔,您可以考慮一個輔助函數,例如:

jQuery.prop = function(name) {
    return function() {
        return this[name];
    }
};

然后,代碼變為:

$("input[id^='product_']").val($.prop('name'));

嘗試這個:

 $("input[id*='product']").each(function() { $this = $(this); $this.val($this.attr("name")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="product_code1" name="Samsung"><br> <input id="product_code2" name="Apple"><br> <input id="product_code3" name="Huawei"><br> <input id="product_code4" name="Motorola"><br> 

$("input[id*='product']").each(function () {
    var $this = $(this);
    $this.val($this.prop("name"));
});

JSFiddle

暫無
暫無

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

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