这个在jquery里面的东西

时间:2013-09-17 20:19:10

标签: javascript jquery json

我如何在每个功能之外使用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(???);
//    });
});

我该怎么做?

提前致谢。

2 个答案:

答案 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,但这应该给你一个想法。