jquery:测试输入变量是否是dom元素 [英] jquery: test whether input variable is dom element

查看:139
本文介绍了jquery:测试输入变量是否是dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to write a jquery function that accepts either a dom element or its id as input:

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

 // Do stuff with myID ...

}

问题:我如何知道我的输入是否是一个dom元素?

Question: How can I tell whether myinput is a dom element???

推荐答案

p>更容易做相反的检查 - 检查它是否是一个字符串,如果使用它来获取一个ID,否则将其视为DOM节点/元素,并处理它,就像它是一个。

It's easier to do the check the other way around - check if it's a string if so use it to get an ID else treat it as a DOM node/element and handle it as if it was one.

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抽象界面。 查看MDC 了解有关HTMLElement的更多信息。

or if you really want to check against if it's HTMLElement then every DOM html element extends HTMLElement abstract interface. Check MDC for more info on HTMLElement.

    ...

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

    ...

最终赢了真的很关心你的电话!

In the end it won't really matter... your call!

汤姆

这篇关于jquery:测试输入变量是否是dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆