简体   繁体   中英

jQuery future elements selector

I have done a simple selector for example:

$('div').eq(0).selector;// returns     "div.slice(0,1)"
$($('div').eq(0).selector);// would not work... 

should the eq(0) not had been there it would work as it wont have the slice but a proper usable selector.

My problem is that, I wonder that using .selector , is not very helpful, and I have not tried other filters etc...

$('div').children().selector// returns "div.children()"

I am using jQuery 1.7.1, I really don't see what the use of this .selector is for when it returns something that does not even work.

I was trying to make a plugin, but I thought of using the .selector to get elements added in the future (on the fly).

UPDATE

$.fn.myplugin(function (){
  $(this.selector)//select future elements...
})

Or is there another approach to this?

If you are making a plugin, what you would typically do is to provide an option with the selector to be used to refresh you list of elements. This option can also be exposed to the end-user so it can be customized.

$('div').myPlugin({
    elements: 'ul > li'
});

If the need to detect future elements to bind events , use event delegation using .on() .

Long story short, you actually define an event handler on a container. The event will bubble up to the container and be executed if the element originally receiving the event matches the specified selector.

<div id="container">
    <span>Some text</span>
    <button>Click me</button>
</div>

$('#container').on('click', 'button', function() { ... });

This will bind one handler on the element #container and the event handler will be executed if an element <button> is clicked... but also for any <button> element added to the DOM afterwards.

Use selector expressions

$('div:eq(0)').selector; // returns 'div:eq(0)'

More here .

You would have to listen for DOM changes, for that see this answer .

OR

You could check for changes to your matched root element every n seconds using a setInterval .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM