简体   繁体   English

设置 title 属性为 Javascript function

[英]Setting title attribute with Javascript function

I am trying to find, if I can pass a value on the title attribute of a label element using Javascript?我正在尝试查找是否可以使用 Javascript 在label元素的title属性上传递一个值?

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?如果是,正确的语法是什么?

<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. 它首先选择标签,然后设置属性。

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>

Demonstration 示范

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) (这不是真的不推荐)

Try this way:- 试试这种方式: -

HTML: HTML:

<label id="lab">TEST</label>​

JS: JS:

window.onload = function() {
    document.getElementById('lab').setAttribute('title','mytitle');
    alert(document.getElementById('lab').title);
}​

Refer LIVE DEMO 参考现场演示

I got this!我懂了! If you are using angular you can use this data Binding and call the function如果您使用的是 angular,则可以使用此数据绑定并调用 function

<label title="{{myFunction()}}">TEST</label>

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

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