我如何在每个功能之外使用this.something
$(function(){
var json = '{ "list": [ { "something": "my string", "stuff": "this" }, { "something": "string of me", "stuff": that } ] }';
$.getJSON(json, function (data) {
$.each(data.list, function() {
$( "#someclassthatdoesntmatter" ).append("<div class='somediv'>"+something+"</div>")
//here this.something is defined
});
});
//here I want to alert a 'something' on clicking the 'somediv' which it appended to
//didn't come further than:
//$(document).on('click', '#somediv',function(){
// alert(???);
// });
});
我该怎么做?
提前致谢。
答案 0 :(得分:0)
$.getJSON(json, function (data) {
$.each(data.list, function() {
UseObject(this);
});
});
});
function UseObject(obj)
{
alert($(obj).something);
}
答案 1 :(得分:0)
可以这样做:
在DOM Ready上:
$('#someclassthatdoesntmatter').on('click', '.somediv', function() {
alert($(this).data('something'));
});
其他地方:
$.getJSON(json, function (data) {
$.each(data.list, function() {
$("#someclassthatdoesntmatter").append('<div class="somediv" data-somthing="' + something + '">' + something + '</div>');
});
});
理想情况下,你不应该在循环中追加DOM,但这应该给你一个想法。