Javascript 如何使用javascript更改<a>的innerText
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6427071/
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
How to change the innerText of an <a> using javascript
提问by harishtps
When I click on the "show details" link it should change to "hide details". I tried the following code but it's not working:
当我单击“显示详细信息”链接时,它应该更改为“隐藏详细信息”。我尝试了以下代码,但它不起作用:
out.print("<a href=\"javascript:parent.showHideDetails('"+id+"',this);\">show details</a>");
function showHideDetails(id,obj) {
try
{
alert(obj.innerText);
obj.innerText = 'hide details';
}
catch (err)
{
alert(err);
}
}
回答by Yhn
The problem is that this
in your href attribute doesn't point to the anchor. You could pass an identifier there, and give the anchor element the same identified as id
attribute; and then use document.getElementById to get the anchor.
问题是this
在您的 href 属性中没有指向锚点。您可以在那里传递一个标识符,并为锚元素赋予与id
属性相同的标识;然后使用 document.getElementById 获取锚点。
Example:
例子:
out.print("<a href=\"javascript:parent.showHideDetails('"+id+"','anchor_1');\" id=\"anchor_1\">show details</a>");
function showHideDetails(id,identifier) {
try
{
var obj = document.getElementById(identifier);
alert(obj.innerText);
obj.innerText = 'hide details';
}
catch (err)
{
alert(err);
}
}
回答by user113716
The details in your question are sparse. Here are a few possibilities:
您问题中的细节很少。这里有几种可能性:
Remove parent.
from the inline handler, and change it to an onclick
:
parent.
从内联处理程序中删除,并将其更改为onclick
:
"<a href=\"#\" onclick=\"javascript:showHideDetails('"+id+"',this);\">show details</a>"
Perhaps the showHideDetails()
function isn't global
也许该showHideDetails()
功能不是全局的
Perhaps innerText
isn't supported in the browser you're using. Try innerHTML
instead.
innerText
您使用的浏览器可能不支持。试试吧innerHTML
。
obj.innerHTML = 'hide details';
回答by meteorainer
InnerText is one of those browser finicky ones that are named differently in different browsers. If you are just getting started with javascript I would recommend using a framework like jQuerybecause it's far simpler to call a function like:
InnerText 是那些在不同浏览器中命名不同的浏览器挑剔者之一。如果您刚刚开始使用 javascript,我建议您使用像jQuery这样的框架,因为调用如下函数要简单得多:
$('#linkID').text('show');
Than it is to get each browser variant set properly. The framework does all that for you.
而不是正确设置每个浏览器变体。该框架为您完成所有这些工作。
回答by Boopathi Rajaa
this
will point to DOM window and not the <a>
tag. So use onclick
attribute to execute.
this
将指向 DOM 窗口而不是<a>
标签。所以使用onclick
属性来执行。
out.print("<a href=\"#\" onclick=\"showHideDetails('"+id+"',this);\">
show details</a>");