Javascript 使用 JQuery 检查 DIV id 是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4170774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:13:43  来源:igfitidea点击:

Check if a DIV id exists with JQuery

javascriptjquery

提问by Marcus

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. 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.

在下面的脚本中检查文档中是否存在 DIV。但是它不起作用。我对 Javascript 没有太多经验;但从我所做的研究来看,我的问题似乎与嵌套函数有关。

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>

回答by Aishwar

You would have to do document.getElementById(id). But seeing how you are using jquery - you could also do $(id).length > 0to check if the element exists

你必须这样做document.getElementById(id)。但是看看你是如何使用 jquery - 你也$(id).length > 0可以检查元素是否存在

回答by Bob Black

Your case is incorrect in your sample code. You should be invoking getElementById, with a lowercase d. Javascript is case sensitive.

您的示例代码中的案例不正确。您应该使用小写的 d 调用 getElementById。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。