I'm creating an element and then inserting it, but it isn't quite working as expected. To create the element:
var showChildren = $("<span>", { text: "[arrow]", class: "show-children" });
Then to insert it, i tried:
$("body").append(showChildren);
But nothing was displayed, so I inspected the object then tried this instead:
$("body").append(showChildren[0].outerHTML);
This displays the element as expected, but seems a little awkward. My goal is to then attach an event handler to it. I thought something like this might work:
showChildren.on("click", function(e) {
$(this).siblings("ul").toggle();
});
But that doesn't work. Is there a better way to create an element, display it, and attach a listener to it?
For appending, unless there's a compelling reason, just build the HTML manually without using jQuery:
$('body').append('<span class="show-children">[arrow]</span>');
For the event, use delegation:
$('body').on('click', '.show-children', function (e) {
$(this).siblings('ul').toggle();
});
You can do the event attachment in your document ready handler, once, and it will fire no matter how many times you append that HTML.
As for a better way, I don't know whats better, it could all just be subjective per developer. But here is another way to create, append and attach listener using chaining.
$("<span>", {
text: "[arrow]",
class: "show-children"
}).appendTo('body').on("click", function (e) {
$(this).siblings("ul").toggle();
});
And the code you wrote above seems to work fine in fiddle: http://jsfiddle.net/b5tb4mer/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.