繁体   English   中英

获取标签内文本的值 Javascript

[英]Get Value of text inside label Javascript

我环顾四周寻找答案,但到目前为止没有成功。 我所拥有的是一个包含带有标题的单选按钮的 div

<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>

现在我要做的是在单击该标签时获取标签内的文本。 不是单选按钮的 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

编辑:

回应评论,Firefox 中不存在innerText。 所以这样做的方法真的是: evt.target.innerText || evt.target.textContent;

谢谢@Ruslan Osmanov

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM