使用JQuery嵌套HTML标记

Ben*_*jin 2 html javascript jquery

我正在学习JQuery,我希望有一个链接列表,当点击时会触发另一个Javascript函数.我现在拥有的代码(下面)使<li>标记成功,但内部JQuery返回一个对象("1. [object Object]")而不是带有链接标记的文本.

$('<li></li>', {
    text: $('<a></a>', {
        text: data[i].name,
        onclick: 'doSomething()'
    }),
    id: 'response'
}).appendTo('ol.responseList');
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

Roc*_*mat 5

html而不是text.

$('<li></li>', {
    html: $('<a></a>', {
        text: data[i].name,
        onclick: 'doSomething()'
    }),
    id: 'response'
}).appendTo('ol.responseList');
Run Code Online (Sandbox Code Playgroud)

PS我建议不要使用onclick属性来绑定事件.使用jQuery的事件API.

$('<li></li>', {
    html: $('<a></a>', {
        text: data[i].name
    }).click(doSomething),
    id: 'response'
}).appendTo('ol.responseList');
Run Code Online (Sandbox Code Playgroud)

更新:如果你想传递idoSomething,你需要做这样的事情(在循环之外):

function createFunc(i){
    return function(){
        doSomething(i);  // this will be the correct value of `i`
    };
}
Run Code Online (Sandbox Code Playgroud)

然后这样做:

$('<li></li>', {
    html: $('<a></a>', {
        text: data[i].name
    }).click(createFunc(i)),  // Yes, this should be `createFunc(i)`, it returns a function
    id: 'response'
}).appendTo('ol.responseList');
Run Code Online (Sandbox Code Playgroud)