检查JQuery是否存在DIV ID [英] Check if a DIV id exists with JQuery
问题描述
我正在使用Javascript来测试文档中是否存在ID为"test_div"的DIV.
Using Javascript I'm trying to test whether or not a DIV with the id "test_div" exists in the document.
我正在使用
if (getElementById("test_div"))
在下面的脚本中
检查DIV是否存在于文档中.但是,它不起作用.我对JavaScript没有太多的经验;但是从我所做的研究来看,似乎我的问题可能与嵌套函数有关.
in the below script to check if the DIV exists in the document. However it does not work. I don't have very much experience with Javascript; but from the research I have done it seems like my problem might have something to do with the nested function.
如果删除
if (getElementById("test_div"))
有没有人知道如何从函数中检查文档ID是否为"test_div"的DIV,如下所示?
Does anyone know how to check if a DIV with the id "test_div" exists in the document from within the function as shown below?
<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>
推荐答案
您将必须执行document.getElementById(id)
.但是,看看您如何使用jquery-您还可以执行$(id).length > 0
来检查元素是否存在
You would have to do document.getElementById(id)
. But seeing how you are using jquery - you could also do $(id).length > 0
to check if the element exists
这篇关于检查JQuery是否存在DIV ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!