-1

我将如何使用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(???);
//    });
});

我该怎么做?

提前致谢。

4

2 回答 2

0
$.getJSON(json, function (data) {
    $.each(data.list, function() {
        UseObject(this);
        });
    });

});

function UseObject(obj)
{
    alert($(obj).something);
}
于 2013-09-17T20:33:11.843 回答
0

可以做这样的事情:

在 DOM 就绪时:

$('#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,但这应该会给您一个想法。

于 2013-09-17T20:48:18.433 回答