嗨,我正在尝试从 <li>
之间单击的单词获取文本。从另一个 jquery 函数创建的标签。
此函数添加 <span>
每个单词周围都有标签,单击任何单词时,它应该显示单击的文本。单独测试时效果很好。
唯一的问题是它不起作用,因为文本是在页面加载后生成的,所以我需要创建这个函数 .live('click' function ()
等等等等....
我一生都无法获得正确的语法。
有什么建议吗?
$('li.ingredient').contents().each(function(_, node) {
var nodelist = node.textContent.split(/\s/).map(function( word ) {
return $('<span>', {
text: word + ' ',
click: function() {
alert( $(this).text() );
}
}).get(0);
});
$('li.ingredient').empty().append(nodelist);
});
最佳答案
原生 Array 对象没有提供 map
方法。
尝试这样的事情:
$('li.ingredient').contents().each(function(_, node) {
// array of words
var nodelist = $(node).text().split(/\s/);
var str = "";
for (var i = 0; i < nodelist.length; i++) {
str += "<span>" + nodelist[i] + " </span>";
}
$('li.ingredient').html(str).find("span").click(function(){
alert($(this).text());
});
});
关于jquery - 显示单击单词的文本。 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9302522/