Javascript 获取用 Anchor 标签编写的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8643780/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:53:07  来源:igfitidea点击:

Get text written in Anchor tag

javascriptjquery

提问by Yogesh

<td class="td1">
<input name="CheckBox" id="c1" type="checkbox" CHECKED="" value="on"/>
<a class="a_c" id="a1">
</td>

If I know ID of Check box $(#c1)then how can I get text of Anchor tag?

如果我知道复选框的 ID,$(#c1)那么如何获取锚标记的文本?

回答by Umesh Patil

If you are not using jQuery, then below line would help.

如果您不使用 jQuery,那么下面的行会有所帮助。

document.getElementById('a1').innerHTML

回答by abuduba

First you have to write a close this tag

首先你必须写一个关闭这个标签

<input name="CheckBox" id="c1" type="checkbox" CHECKED="" value="on"/>
<a class="a_c" id="a1"> Something </a>

Anchor has id assigned yet therefore you can get access directly:

Anchor 已经分配了 id,因此您可以直接访问:

$("#a1").text()

If anchor did not have id and will be always after checkbox ( can be separated by other tags)

如果锚没有 id 并且总是在复选框之后(可以用其他标签分隔)

$('#c1').next("a").text();

otherwise if will be checkbox's sibling and in this branch is one anchor ( not necessarily just after checkbox)

否则 if 将是复选框的兄弟,并且在此分支中是一个锚点(不一定就在复选框之后)

 $('#c1').parent().find("a").text();

回答by Sudhir Bastakoti

$('#c1').next("a").text();

回答by Exit

I'm adding a pure Javascript answer that doesn't rely on .innerHTML, which can be much slower than proper DOM level accessors. This also assumes you are retrieving HTML free content.

我正在添加一个不依赖于 的纯 Javascript 答案.innerHTML,这可能比正确的 DOM 级别访问器慢得多。这也假设您正在检索 HTML 免费内容。

Using the original question with a completed a tag:

使用带有完整标签的原始问题:

<td class="td1">
<input name="CheckBox" id="c1" type="checkbox" CHECKED="" value="on"/>
<a class="a_c" id="a1">Something wonderful</a>
</td>

Javascript using the id from the anchor tag:

使用锚标记中的 id 的 Javascript:

document.getElementById("a1").textContent;

If you need to support Internet Explorer 8 or lower, you'll have to either selectively use .innerTextfor IE 6-8, or stick with .innerHTML. .innerTextwas not supported by Firefox for a while, so it shouldn't be used for anything but IE 6-8.

如果您需要支持 Internet Explorer 8 或更低版本,则必须有选择地使用.innerTextIE 6-8,或者坚持使用.innerHTML. .innerTextFirefox 有一段时间不支持它,所以它不应该用于 IE 6-8 以外的任何东西。

回答by Exit

If the anchor tag has an ID as in your example, then $('#a1').text();should do the trick.

如果锚标记具有您的示例中的 ID,那么$('#a1').text();应该可以解决问题。

回答by davidethell

Like this:

像这样:

$('#c1').next().text();