【问题标题】:Checking if a button exists检查按钮是否存在
【发布时间】:2013-12-02 15:18:29
【问题描述】:

我有一个由几个 .jsp 页面调用的 .js 文件。在这个特定的 .js 文件中,我需要做的是仅当 .jsp 页面中存在“保存”按钮时才调用某个函数。如何检查按钮是否存在?目前,在 .js 文件中,按钮是这样引用的: $('button[id=save]')

如何检查这样的按钮是否存在?

【问题讨论】:

标签: javascript jquery html jsp button


【解决方案1】:

试试这样的

$(document).ready(function(){
    //javascript
    if(document.getElementById('save')){
        //your code goes here
    }
    
    //jquery
    if($('#save').length){
        //your code goes here
    }
});

【讨论】:

  • +1 getElementById 就够了,你可以去掉 jQuery 部分 :)
【解决方案2】:

你可以这样做:

if($('#save').length > 0){
    // Button exists
} else {
    // Button is not present in the DOM yet

}

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多