Reputation: 35
Hi I'm trying to get the text from a clicked word in between <li>
tags that is created from another jquery function.
This function adds <span>
tags around each word and on click of any word it should display the clicked text. This works fine when tested seperately.
Only problem is it doesn't work because the text is generated after the page load so I need to make this function .live('click' function ()
etc etc ....
I can't for the life of me get the syntax right.
Any suggestions??
$('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);
});
Upvotes: 2
Views: 235
Reputation: 207861
How about this example: jsFiddle.
This example has a list where the button adds some random words, each wrapped in a span tag. When you click any word it's value is logged to the console.
jQuery:
$('button').click(function(){
$('li').append('<span>foo</span> ');
});
$('li').on('click','span',function(e){
console.log($(this).text());
});
Upvotes: 0
Reputation: 95031
The native Array object does not come with a map
method.
Try something like this:
$('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());
});
});
Upvotes: 2