我的网站的每个页面都有一组不同的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
调用中包装每个选择器,以便脚本不会中断?
感谢您重申jQuery自动执行此操作。事实证明,问题在于对'document.getElementById()'的调用破坏了一切。我切换到一个jQuery调用,一切都很好。谢谢! – 2012-01-28 19:11:44