Javascript 从输入文本中获取属性值

Javascript 从输入文本中获取属性值,javascript,jquery,Javascript,Jquery,我想得到每个输入字段的属性值 <input type="text" id="qty" data-id="{{$item->rowid}}" value="{{$item->qty}}"> function goUpdateCart(){ $('input[type=text]').each(function(){ alert($('input[type=text]').getAttribute("data-id")); }) }

我想得到每个输入字段的属性值

<input type="text" id="qty" data-id="{{$item->rowid}}" value="{{$item->qty}}">

function goUpdateCart(){

    $('input[type=text]').each(function(){

        alert($('input[type=text]').getAttribute("data-id"));
    })
}

函数goUpdateCart(){
$('input[type=text]')。每个(函数(){
警报($('input[type=text]')。getAttribute(“数据id”);
})
}
我的功能无法正常工作

请尝试以下操作:

$('input[type=text]').each(function(){
     alert($(this).attr("data-id"));
});

您需要在每个函数中使用每个迭代元素上下文
this
,将当前元素与
.attr('data-id')
.data('id')
一起作为目标:


函数goUpdateCart()
{
var属性=$(“#数量”).attr('data-id');
警报(属性);
}
嗯,
.getAttribute(“数据id”)不是jquery方法。
您可以使用以下任一项来获取
数据-*attr

$(this).data('id');
$(this).attr('data-id');
$(this).prop('dataset').id;
this.dataset.id;  
所以它可以是上面的任何一个:

function goUpdateCart(){

    $('input[type=text]').each(function(){

        alert(this.dataset.id);
    })
}

$(this).data('id')
$('input[type=text]').attr(“data id”)
$(this.attr(“data id”)
this.getAttribute(“data id”)
$(this.data('id')
$(this.attr('data-id'))-如T.J.Crowder所述,data管理jQuery的数据缓存,而不是data-*属性。jQuery将从data-*属性初始化数据缓存,但使用数据作为setter不会设置属性;通过data读取数据后设置属性不会更新数据的副本。示例:@C0dekid.php:什么答案?在我之前已经发布的答案是不正确的。它正在获取id而不是数据id。为什么不简单地
this.dataset.id
而不是
$(this.prop('dataset').id
$(this).data('id');
$(this).attr('data-id');
$(this).prop('dataset').id;
this.dataset.id;  
function goUpdateCart(){

    $('input[type=text]').each(function(){

        alert(this.dataset.id);
    })
}