15

I am trying to find, if I can pass a value on the title attribute of a label element using Javascript?

I have tried the following Javascript code:

function myFunction()
{
    return "Hello!";
}

And a piece of HTML code:

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

But, this isn't working. It just show the 'myFunction()' as a text.

Is it possible, what I am trying to do? If yes, what is the correct syntax?

4

3 回答 3

29
<label id='mylabel'>TEST</label>
<script>
    function myFunction() {
        return "Hello!";
    }

    document.getElementById('mylabel').setAttribute('title', myFunction());
</script>

应该做的工作。它首先选择标签,然后设置属性。

于 2012-10-09T20:07:48.940 回答
9

你不能像这样内联javascript。

你可以做的是

1)给你的标签一个id,把它放在你身体的最后

<script>
   document.getElementById('myId').title = myFunction();
</script>

示范

2)如果您真的想内联调用,请在您想要标签的位置写下:

<script>
     document.write('<label title="'+myFunction()+'">TEST</label>');
</script>

(这个真的不推荐)

于 2012-10-09T20:06:02.967 回答
6

试试这种方式: -

HTML:

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

JS:

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

参考现场演示

于 2012-10-09T20:11:27.830 回答