关于非现在元素的jQuery事件 [英] jquery events on non-present elements

查看:122
本文介绍了关于非现在元素的jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下(基于PHP)将事件与不在页面上的ids进行绑定是否不好?会是否会导致代码错误和缓慢,否则jQuery会自动忽略它们?

Is it bad to tie events to ids that aren't on the page in certain circumstances (based on PHP)? Will it cause code errors and slowness, or will jQuery automatically ignore them?

我应该在每个可能不在的元素上放置如下所示的内容吗? >

Should I instead put something like the following on every element that might not be there?

if ( $('#element') ){
    $('#element').click(function(event) {}
}

我的页面设置是某些条件下没有加载某个编辑框保持功能不被尝试..我设置了一个有条件的PHP包,因为它是基于数据库中的情况,我真的不想传递到前端。

My page setup is a certain edit box is not loaded under certain conditions to keep functions from being tried.. I set it up with a conditional php include because it's based on circumstances in the database that I don't really want to pass through to the front-end.

现在,页面上的所有js都在一个文件中,具有多个函数。

Right now all the js for the on page is in a single file with a number of functions.

推荐答案

当jQuery选择器没有返回任何元素时,没有事件被绑定,所以如果语句,则不要写而不会损害

When jQuery selector doesn't return any elements, no events are being bound. So you're making no harm by not writing if statement.

这意味着内部的jQuery将事件处理程序绑定到所有匹配的el当没有,没有处理程序将绑定到任何元素。这意味着:您不必在代码中检查元素的存在。

This means that internally jQuery binds event handler to all matched elements. When there are none, no handler will get bound to any element. This means: you don't have to check element existence in your code.

每当你在做

if ( $('#element') ){
    $('#element').click(function(event) { /* blah blah */ });
}

您应该保存选择器结果

var result = $('#element');

// check number of elements (zero equals false, anything else equals true)
if (result.length) {
    result.click(function(event) {
        // blah blah
    });
}

result.length result.size()相同

如果您的界面将生成新元素,并希望在添加到DOM时将其附加到eevent处理程序,那么您应该使用 delegate()函数。还有 live()函数,但尽可能使用第一个,因为它是一个更好的选择。网上有很多资源为什么这是真的。 This Stackoverflow answer

If your interface will generate new elements and you'd like them to have eevent handlers attached when they get added to DOM, then you should use delegate() function. There's also live() function but use the first one whenever possible, because it is a better alternative. There are numerous resources on the net why this is true. This Stackoverflow answer for instance.


注意:从jQuery 1.7开始,.delegate()已被。on()方法。然而,对于早期版本,它仍然是使用事件委托的最有效手段。

Note: As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation.

请参阅 jQuery文档

这篇关于关于非现在元素的jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆