2012-01-28 50 views
0

我的网站的每个页面都有一组不同的jQuery特效以及使用ajax提交的表单。我遇到了一个空的jQuery选择器阻止其他javascript运行的问题。例如:空的jQuery选择器打破了脚本的其余部分

// site.js 
$(document).ready(function() { 

function changeText() { 
$("#div1").html("Test 1"); 
$("#div2").html("Test 2"); 
} 

$("#button1").click(changeText()); 
$("#button2").click(changeText()); 

}); 

// page1.html 
<script src="/static/jquery.js"></script> 
<script src="/static/site.js"></script> 
<div id="div1">Div 1</div> 
<input type="button" value="Change" id="button1"> <!-- Works //--> 

// page2.html 
<script src="/static/jquery.js"></script> 
<script src="/static/site.js"></script> 
<div id="div2">Div 2</div> 
<input type="button" value="Change" id="button2"> <!-- Doesn't work //--> 

我到目前为止的解决方案是为每个页面创建单独的javascript文件,但必须有其他方法。有任何想法吗?我是否真的需要在if $("selector").length调用中包装每个选择器,以便脚本不会中断?

回答

0

不,你不需要在jquery检查emptyundefined,它是由implicitlyjquery

也可以改写为下面的代码,更少的代码更好的性能

$("#button1,#button1").click(function(){ 
    $("#div1").html("Test 1"); 
    $("#div2").html("Test 2"); 
}); 
+0

感谢您重申jQuery自动执行此操作。事实证明,问题在于对'document.getElementById()'的调用破坏了一切。我切换到一个jQuery调用,一切都很好。谢谢! – 2012-01-28 19:11:44

2

我不知道这是否是问题,但你没有正确地声明点击事件处理程序:

$("#button1").click(changeText()); 

如果你把括号,该函数直接调用。

应该是:

$("#button1").click(changeText); 

据我所知,jQuery的总是返回,如果没有DOM元素被匹配它根本不包含任何元素(长度= 0)。

+0

如果我需要传递一个参数,所以我可以做一个典型的'e.preventDefault();'? 此外,当我在我的例子中声明函数时,是否应该在'$(document).ready()'函数内部进行? – 2012-01-28 17:23:15

+0

当调用事件处理程序时,jquery将自动传递事件对象,只需在函数'function changeText(e){...}'中声明该参数即可。你不必把它们放在准备好的处理程序中。 – 2012-01-29 10:26:46