[英]Jquery - How to add text from attribute name from input into label attr for and that input ID?
我不知道如何將輸入中的名稱添加到標簽attr中以及與ID相同的輸入。 他們在同一個div。 你們知道怎么做嗎? 謝謝。
jQuery的:
$('input[type="text"]').each(function () {
var name = $("input").attr("name");
})
HTML:
<div data-role="fieldcontain">
<label>Name:</label>
<input type="text" name="fname" value="" />
</div>
只需獲取this
輸入字段的前一個元素,並使用this.name
更改其文本:
$('input[type="text"]').each(function() {
$(this).prop('id', this.name) // set 'id' of input field
.prev('label') // get previous sibling element
.attr('for', this.name); // set 'for' attribute
});
使用$(this)
$('input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).prev('label').text(name);
})
使用.prop()而不是.attr()因為, attr()為你提供了在頁面加載的html中定義的元素值。 總是建議使用prop()來獲取通過javascript / jquery修改的元素的值,因為它給出了元素當前狀態dom元素的原始值
$('input[type="text"]').each(function () {
var name = $("input").prop("name");
$(this).prev('label').text(name);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.