简体   繁体   English

jQuery未来元素选择器

[英]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. 如果不存在eq(0) ,它将起作用,因为它没有分片,但有合适的可用选择器。

My problem is that, I wonder that using .selector , is not very helpful, and I have not tried other filters etc... 我的问题是,我想知道使用.selector不是很有帮助,我还没有尝试过其他过滤器等。

$('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. 我正在使用jQuery 1.7.1,当它返回甚至无法正常工作的东西时,我真的看不到这个.selector的用途。

I was trying to make a plugin, but I thought of using the .selector to get elements added in the future (on the fly). 我试图制作一个插件,但是我想到了使用.selector来获取将来添加的元素(即时)。

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() . 如果需要检测将来要绑定事件的元素,请使用.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. 这将在元素#container上绑定一个处理程序,并且如果单击元素<button> ,则事件处理程序将被执行...以及随后添加到DOM中的任何<button>元素也将执行。

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 . 您将不得不听DOM的更改,为此请参见答案

OR 要么

You could check for changes to your matched root element every n seconds using a setInterval . 您可以使用setInterval每n秒检查一次对匹配的根元素的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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