Javascript Javascript获取自定义按钮的文本值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10351658/
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
Javascript get custom button's text value
提问by hacket
I have a button that is defined as follows :
我有一个定义如下的按钮:
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
and I'm trying to grab it based on the text value, however, none of it's attributes contain the text value. It's generated in a pretty custom way by the look of it.
我试图根据文本值来获取它,但是,它的属性都不包含文本值。从外观上看,它是以一种非常自定义的方式生成的。
Does anyone know of a way to find this value programatically, besides just going through the html text? Other than attributes?
除了通过 html 文本之外,有没有人知道以编程方式找到这个值的方法?除了属性?
Forgot one other thing, the id for this button changes regularly, and using jquery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
忘了另一件事,这个按钮的 id 会定期更改,使用 jquery 抓取它会导致由于某种原因破坏页面。如果你需要任何关于我为什么需要这个的背景,让我知道。
This is the javascript I am trying to grab it with:
这是我试图抓住它的javascript:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
它只返回代码中定义的三个属性。
innerHTML, text, and textContent all come back as null.
innerHTML、text 和 textContent 都返回为 null。
采纳答案by Richard Connamacher
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
如果您试图完全通过其文本内容来定位按钮,我会抓取所有按钮的列表并遍历它们以找到这个:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
当然,如果这个按钮的内容稍有改变,你的代码也需要更新。
回答by ThiefMaster
You can do that through the textContent
/innerText
properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
您可以通过textContent
/innerText
属性(依赖于浏览器)来做到这一点。这是一个无论浏览器使用哪个属性都可以工作的示例:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
你也可以使用 jQuery 来做到这一点:
alert($('#ext-gen26').text());