当我尝试附加数据 ID 时;我收到一个错误

When I'm trying to append data-id; I got an error

本文关键字:错误 一个 数据 ID      更新时间:2023-09-26

看看这个:这是一个工作正常的简单代码

.html

<select></select>
<button id="btn1">click me</button>

.js

$('#btn1').on('click',function(){
    var select = $('select');
    select.append($('<option>').val('v2').text('text2'));
});

当我尝试附加数据 ID 时,我遇到了错误。有什么帮助吗?

select.append($('<option>').val('v2').text('text2').data-id('id1'));

http://jsfiddle.net/omarmakled/QQ44U/

你可以用2种方式做到这一点

select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));

select.append($('<option>').val('v2').text('text2').data('id', 'id1'));


http://api.jquery.com/data/http://api.jquery.com/attr/

首先,data-id字符串在 JS 中是非法标识符(因为它包含连字符),因此即使它可以作为 jQuery 对象方法使用,您也应该这样称呼它......

someObj['data-id'](someId);

显然,对于如此简单的操作来说,这太混乱了。事实上,jQuery.prototype 中没有定义这样的方法 - 而是希望你使用 attr()(显式设置任何属性)或data()(特定于数据集 API 的属性)。

作为旁注,您不必打那么多电话:这...

select.append($('<option>', {
  value: 'v2',
  text: 'text2',
  'data-id': 'id1'
}));

。更具可读性和效率。请注意"data-id"两边的引号:对象属性只有在正确的JS标识符时才能不加引号。

JSFiddle.

正确的使用方法是data()

select.append($('<option>').val('v2').text('text2').data('id','id1'));

或者,如果你想要一个实际的属性,你可以使用attr()

select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));
相关文章: