问题
I'm trying to construct a set of options for a select element, using jQuery. It's working except for the data attribute that should be included, which seems to being ommitted.
Here is my code:
// cJ is JSON object.
// #currency is my select element.
function makeCurDropDown(cJ) {
$.each(cJ, function (i) {
$('#currency').append(
$('<option></option>').val(i).data("sym", cJ[i][0]).html(cJ[i][1])
);
});
}
回答1:
Actually the data is set, but since you are using data method instead of the attr method, it's not visible. jQuery stores the value behind the scenes, for getting the value you can use .data('sym'). If you want to set the value as an attribute you can use attr method instead.
来源:https://stackoverflow.com/questions/18254213/append-select-option-with-an-html5-data-attribute-using-jquery