简体   繁体   English

检查JQuery是否存在DIV id

[英]Check if a DIV id exists with JQuery

Using Javascript I'm trying to test whether or not a DIV with the id "test_div" exists in the document. 使用Javascript我正在尝试测试文档中是否存在ID为“test_div”的DIV。

I'm using 我正在使用

if (getElementById("test_div"))

in the below script to check if the DIV exists in the document. 在下面的脚本中检查文档中是否存在DIV。 However it does not work. 但它不起作用。 I don't have very much experience with Javascript; 我对Javascript没有太多经验; but from the research I have done it seems like my problem might have something to do with the nested function. 但是从我所做的研究来看,似乎我的问题可能与嵌套函数有关。

The script does work if I remove the 如果我删除了该脚本,该脚本确实有效

if (getElementById("test_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? 有谁知道如何检查文件中是否存在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>

You would have to do document.getElementById(id) . 你必须做document.getElementById(id) But seeing how you are using jquery - you could also do $(id).length > 0 to check if the element exists 但是看看你如何使用jquery - 你也可以做$(id).length > 0来检查元素是否存在

Your case is incorrect in your sample code. 您的示例代码中的案例不正确。 You should be invoking getElementById, with a lowercase d. 你应该使用小写d调用getElementById。 Javascript is case sensitive. Javascript区分大小写。

If you're using jquery, make sure to prefix id with a #, like so $("#test_div"), so jquery knows you want to query for an element id. 如果您正在使用jquery,请确保使用#前缀id,如$(“#test_div”),因此jquery知道您要查询元素ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM