开发者

how to get children elements of an html element

I have a var saved in my JS custom object (code below is from inside the class):

var toolbar;

this.create_toolbar = function(开发者_如何学运维) {
    self.toolbar = document.createElement('div');
    $(self.toolbar)
        .html('<ul>' +
            '<li id="insert_bold"></li>' +
            '<li id="insert_em"></li>' +
            '<li id="insert_hyperlink"></li>' +
            '<li id="insert_code"></li>' +
            '<li id="insert_image"></li>' +
            '</ul>')
        .insertBefore(self.editTextarea); // just a textarea on the page
}

The toolbar gets created and placed successfully, and self.toolbar now holds the object for the new div. However, when trying to bind the <li>'s to clicks I can't seem to get anything to happen:

$(self.toolbar).children("li#insert_bold").click(function() {
    alert("just checking");
});

To be clear, after the above, nothing is happening when I click <li id="insert_bold">

Is there something that I am missing? I am fairly new to jQuery....am I allow to put a variable that holds an [object object] in the $()? If not, how should I do this?


You need to use .find() here, like this:

$(self.toolbar).find("li#insert_bold").click(function() {
  alert("just checking");
});

.children() only looks at immediate children, <li> is beneath the <ul> though, so it's not an immediate child.


Be aware though if you intend on having multiple instances of this on a page (I'm guessing this is likely the case), you should use classes instead (IDs need to be unique), then use a class selector, for example: $(self.toolbar).find("li.insert_bold").


While Nick has solved your question, I don't think this is a good idea, especially if you have a large number of HTML elements binding.

When I have a rather small number, I do gather the items in an object inside the main constructor function

this.el = {
$button : $('.button','#div'),
$submit : $('.submit','#div')
};

Then when I need an element, I just call it with (this), assuming you are using prototype functions.

this.el.$button.click(function () {

});

If you many elements to deal with, 20 or more, I'll recommend that you opt for a JavaScript FrameWork. Backbone Js is a good one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜