使用 Javascript 函数设置标题属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12807603/
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
Setting title attribute with Javascript function
提问by Redg
I am trying to find, if I can pass a value on the title
attribute of a label
element using Javascript?
我正在尝试查找,是否可以使用 Javascripttitle
在label
元素的属性上传递值?
I have tried the following Javascript code:
我尝试了以下 Javascript 代码:
function myFunction()
{
return "Hello!";
}
And a piece of HTML code:
还有一段HTML代码:
<label title="myFunction()">TEST</label>
But, this isn't working. It just show the 'myFunction()' as a text.
但是,这行不通。它只是将“myFunction()”显示为文本。
Is it possible, what I am trying to do? If yes, what is the correct syntax?
有可能吗,我正在尝试做什么?如果是,正确的语法是什么?
回答by dakn?k
<label id='mylabel'>TEST</label>
<script>
function myFunction() {
return "Hello!";
}
document.getElementById('mylabel').setAttribute('title', myFunction());
</script>
Should do the job. It first selects the label and then sets the attribute.
应该做这项工作。它首先选择标签,然后设置属性。
回答by Denys Séguret
You can't inline javascript like this.
你不能像这样内联javascript。
What you may do is
你可以做的是
1) give an id to your label and put this at the end of your body
1)给你的标签一个id,把它放在你身体的末端
<script>
document.getElementById('myId').title = myFunction();
</script>
2) if you really want to inline the call, write this at the point where you want your label :
2)如果你真的想内联调用,在你想要标签的地方写下这个:
<script>
document.write('<label title="'+myFunction()+'">TEST</label>');
</script>
(this is really not recommended)
(这个真的不推荐)