获取标签内文本的值Javascript
问题描述:
我环顾四周寻找答案,但至今未成功。我有什么是含有标题获取标签内文本的值Javascript
<div>
<label title_id="1" function="update_answer_title" class="pure-radio" for="option-1">
<input type="radio" name="1" value="1" id="option-1">
Talking on the phone or sending a text message.
</label>
<label title_id="2" function="update_answer_title" class="pure-radio" for="option-2">
<input type="radio" name="1" value="2" id="option-2">
Having your keys held in your hand, ready to unlock car and/or provide defense.
</label>
</div>
现在我所要做的就是让一个标签中的文本被点击标签时单选按钮一个div。不是单选按钮的html。因此,在我的onclick听众里面,我是迄今为止所尝试的是:
evt.target.childNodes[1].valueOf().innerText
evt.target.childNodes[1].toString()
JSON.stringify(evt.target.childNodes[1])
以及这些尝试的一堆其他排列组合。但每次我都从该值获得,这些正在回归是:
[object Text]
如何转换对象文本到正常的文本?
谢谢!
答
嗯,那是愚蠢的,我想通了,与其做
evt.target.childNodes[1] ...
所有我需要做的是让目标的内文并会自动地过滤掉HTML我这样解决方法是:
evt.target.innerText
编辑:
在回应评论,innerText属性不会在Firefox中存在。所以这样做的方法确实是:evt.target.innerText || evt.target.textContent;
谢谢@Ruslan奥斯曼诺夫
使用'evt.target.textContent || evt.target.innerText'兼容性 –
没错。 'innerText'不是标准的,Firefox没有它。 – Barmar
Firefox自45版开始实施'innerText'!在几次发布之后删除'textContent'可能是安全的。 – TAGraves