开发者

Dynamic selectors in jquery

开发者 https://www.devze.com 2023-02-28 18:24 出处:网络
I have a code similar to t开发者_开发知识库his, where I assign a function to the click even that change the style

I have a code similar to t开发者_开发知识库his, where I assign a function to the click even that change the style

$(".style1, .style2", "#section").click(function () {
    changeStyle($(this));
});

it might happens that the item change from style1 to style2, so the item should be still clickable, but the actions doesn't take effect. Seems that the item list $(".style1, .style2", "#section") is created on load and is not updated when i the stile is changed to include new elements.

I have tried to put the pasted code into a function and call it at the end of the function changeStyle, but this adds another trigger, so when I click in other items with style1 or style2, the actions trigger 2, 3, 4, ... times. And I just one to trigger it once.

How can I solve it?

Thanks for your help.


I don't exactly understand your problem completely, but it sounds like you're creating new elements and dynamically adding event handlers to them dynamically as well.

If this is your problem, you just need to use .delegate(), which will ensure that an event handler is attached to both existing and dynamically created elements later in the lifecycle of your page. This way, you don't have to keep assigning event handlers every time you create an element.

$('#section').delegate('.style1,.style2', 'click', function() {
    changeStyle($(this));
});

Additionally, your changeStyle() function sounds like it can benefit a lot from .toggleClass() or a similar jQuery function.


Try changing your use of 'click' to live. So,

$(".style1, .style2", "#section").live("click", function (e) {
  changeStyle($(e.target));
});

Live means that the selector test is done on click rather than on page load. You can see the documentation here: http://api.jquery.com/live/

0

精彩评论

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

关注公众号