简体   繁体   中英

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

Check this out: here's a simple code that works fine

html

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

js

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

When I'm trying to append data-id I got an error. Any help?

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

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

The correct method to use is data() :

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

Or if you want an actual attribute you can use attr() :

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

You can do this 2 ways

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

or

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

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

First, data-id string is illegal identifier in JS (as it contains hyphen), therefore even if it were available as a jQuery object method, you should have called it like that...

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

Apparently, that's too messy for such a simple operation. In fact, there's no such method defined in jQuery.prototype - which instead expects you to employ either attr() (to set any attribute explicitly), or data() (dataset API specific one).

As a sidenote, you don't have to make that many calls: this...

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

... is both more readable AND efficient. Note the quotation marks around 'data-id': object properties can be non-quoted only if they are proper JS identifiers.

JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM