Mar*_*cus 18 javascript jquery
使用Javascript我正在尝试测试文档中是否存在ID为"test_div"的DIV.
我正在使用
if (getElementById("test_div"))
Run Code Online (Sandbox Code Playgroud)
在下面的脚本中检查文档中是否存在DIV.但它不起作用.我对Javascript没有很多经验; 但是从我所做的研究来看,似乎我的问题可能与嵌套函数有关.
如果我删除了该脚本,该脚本确实有效
if (getElementById("test_div"))
Run Code Online (Sandbox Code Playgroud)
有谁知道如何检查文件中是否存在ID为"test_div"的DIV,如下所示?
<div id="test_div"></div>
<script>
function loadInfo(){
var req = new Request({
method:'get',
url:'getinfo.php,
noCache: true,
onRequest: function(){
if (getElementById("test_div")) {
$('test_div').set('html', 'loading data');
}
},
onComplete:function(responseText, responseHtml){
if (JSON.decode(responseText) != null){
var data = JSON.decode(responseText);
if (getElementById("test_div")) {
$('test_div').set('html', data['test_div']);
}
}
},
onFailure: function(){
if (getElementById("test_div")) {
$('test_div').set('html', '-');
}
}
}).send();
}
window.addEvent('domready', function(){
loadInfo();
});
</script>
Run Code Online (Sandbox Code Playgroud)
Ais*_*war 46
你必须这样做document.getElementById(id)
.但是看看你如何使用jquery - 你也$(id).length > 0
可以检查元素是否存在
Bob*_*ack 11
您的示例代码中的案例不正确.你应该使用小写d调用getElementById.Javascript区分大小写.
如果您正在使用jquery,请确保使用#前缀id,如$("#test_div"),因此jquery知道您要查询元素ID.