【问题标题】:jquery: test whether input variable is dom elementjquery:测试输入变量是否为dom元素
【发布时间】:2011-02-17 20:14:45
【问题描述】:

我想编写一个 jquery 函数,它接受一个 dom 元素或其 id 作为输入:

function myfunction(myinput){
 // pseudocode:
 // if (myinput is dom element){
 //   var myID = $(myinput).attr('id');
 // } else {
 //   var myID = myinput;
 // }

 // Do stuff with myID ...

}

问题:如何判断myinput是否是dom元素???

【问题讨论】:

标签: jquery dom


【解决方案1】:

反过来进行检查更容易 - 检查它是否是字符串,如果是,则使用它来获取 ID,否则将其视为 DOM 节点/元素并像处理它一样处理它。

function myfunction(myinput) {

    var myId;

    if (typeof myinput == 'string'){
        myId = myinput;
    } else {
        myId = myinput.id; // myinput.id is enough
    }

    // do something

}

或者如果你真的想检查它是否是 HTMLElement,那么每个 DOM html 元素都扩展 HTMLElement 抽象接口。 Check MDC 了解有关 HTMLElement 的更多信息。

    ...

    if (myinput instanceof HTMLElement){
        myId = myinput.id; // myinput.id is enough
    } else {
        myId = myinput;
    }

    ...

最终这并不重要......你的电话!

汤姆

【讨论】:

  • 谢谢!这正是我所需要的。
  • HTMLElement 在某些浏览器(可能是 IE8)中不适合我,所以现在我正在检查 nodeType
  • 你可以通过$(myinput).length > 0查看DOM中是否存在元素。
【解决方案2】:

你会像这样实现你的函数:

function myfunction(myinput){

 if (myinput.nodeType){
    var myID = $(myinput).attr('id');
 } else {
    var myID = myinput;
 }

 // Do stuff with myID ...

}

更多关于nodeType的信息。

【讨论】:

  • 这个解决方案+1。 jQuery 代码在其 isPlainObject 函数中使用它来排除 DOM 节点。
【解决方案3】:

我想知道一个好的三元是否可以工作,像这样

var myID = $(myInput).attr('id') ? $(myInput).attr('id') : myInput;

【讨论】:

    【解决方案4】:

    if( myinput instanceof domElement ) alert("Yes");

    【讨论】:

    • 不,没有domElement这样的类。
    • 你的意思是ElementNode ;)
    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2021-09-02
    • 2011-02-04
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多