javascript 获取元素的 ID 并将其与字符串或另一个 ID 进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17428383/
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
Get an element's ID and compare it to a string OR another ID
提问by AquaSoley
How can I get the ID of an element and compare it to a string OR another id ?
如何获取元素的 ID 并将其与字符串或另一个 id 进行比较?
What I would like to do exactly is make a condition that would get the element's ID and compare it to a certain string or another element's ID.
我想要做的正是创建一个条件来获取元素的 ID 并将其与某个字符串或另一个元素的 ID 进行比较。
I have this piece of code right now to compare my id to another id (which obviously doesn't work):
我现在有这段代码可以将我的 id 与另一个 id 进行比较(这显然不起作用):
function Something(elemid)
{
if(elemid == document.getElementById('myid').id)
{
...
}
}
Or this piece of code to compare to a string (doesn't work either):
或者这段代码与字符串进行比较(也不起作用):
if(elemid == "mystring")
{
...
}
This is a simple problem, but still, I can't seem to find anything around here or even on other websites that would be what I am searching for. I can't use any JQuery whatsoever, so any Javascript only anwser would be really appreciated.
这是一个简单的问题,但是,我似乎无法在这里或什至在其他网站上找到我正在搜索的内容。 我不能使用任何 JQuery,因此任何仅使用 Javascript 的 anwser 将不胜感激。
回答by Darren
if(elemid = document.getElementById('myid').id)
{
...
}
You need to compare it using ==
. A single =
is assign.
您需要使用==
. 单个=
是分配。
Also document.getElementById('myid').id
is completely useless. You are specifying the id
directly and then attempt to return it.
也是document.getElementById('myid').id
完全没用的。您正在id
直接指定,然后尝试返回它。
As a simple test to show you how to compare an element.
作为向您展示如何比较元素的简单测试。
<input type="text" id="hello" class="test" />
var element = document.getElementsByClassName("test")[0].id;
if (element === "hello") {
alert("Working");
}
回答by a_p
How are you calling the function from jsp?
你是如何从jsp调用函数的?
This code works for me:
这段代码对我有用:
function getValue(elementId)
{
if(document.getElementById("myHeader").id = elementId)
{
alert('It Works!');
}
}
and in the jsp
并在jsp中
<h1 id="myHeader" onclick="getValue('myHeader')">Click me!</h1>
<h1 id="myHeader" onclick="getValue('myHeader')">Click me!</h1>