When I execute the following script, only one value is displayed in the alert:
<script>
window.onload = function () {
var num = 15;
for (var i = 0; i < 10; i++) {
$('<tr style="background-color: aqua" id = ' + i + '></tr>').appendTo("table");
for (var j = 0; j < 10; j++) {
num++;
$('<td id ='+num+'></td>').appendTo("#"+i);
$('<button>S</button>').data("field", i, j).appendTo("#" + num);
}
}
$('td').on('click', 'button', function () {
var d = $(this);
alert(d.data("field")); // here alert shows one variable
});
}
</script>
How can I store two values in the element's data? Maybe I can send an array?
The data you store using the jQuery data method can be an object. So you can store the values this way:
$('<button>S</button>').data("field", { i: i, j: j});
And read them out again like this:
var d = $(this),
field = d.data("field");
alert(field.i);
alert(field.j);
You should also look into using jQuery's ready method instead of window.onload
.
You can set them as object
or array
.
$('<button>S</button>').data("field", [i,j] ).appendTo("#" + num);
and alert them using
alert( d.data("field").join(',') ); // here alert shows one variable
as per comment " Calling join(",") is not actually necessary, the override of toString() implemented by arrays already performs this operation. " . so you can all simply
alert( d.data("field") );
check this on http://jsfiddle.net/xhPjh/
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.