简体   繁体   English

如何使用JavaScript更改<a>标签中的title属性?

[英]How to change title attribute in <a> tag using JavaScript?

I have a html tag , in that initially I want tooltip name as mentioned in the "title" attribute. 我有一个html标签,最初我想要“标题”属性中提到的工具提示名称。 After I click on the link, I want different tooltip name. 点击链接后,我想要不同的工具提示名称。 I have used the below code but it is not working. 我使用了以下代码,但它无法正常工作。 Can anyone please help me? 谁能帮帮我吗?

<html>
<head>
<script>

function tool(){
document.getElementsByName(link).title = "after click";
}

</script>
</head>
<body>
    <a href="javascript:tool()" name ="link" title="before click">click here</a>
</body>
</html>

I am assuming this is just a simplified example of what you want to do, since changing the link onclick can be done inline: 我假设这只是您想要做的简化示例,因为更改链接onclick可以内联完成:

 <a href="#" onclick="this.title='after click'" title="before click">...</a>

Either way, the best way is to avoid doing any lookups altogether. 无论哪种方式,最好的方法是避免完全进行任何查找。 Simply pass in the reference to your link as a parameter to your function: 只需将对链接的引用作为参数传递给您的函数:

<script>
  function tool(link) {
    link.title = 'after click';
  }
</script>
<a href="#" onclick="tool(this)" title="before click">...</a>

Naturally, as Grant suggests, you can pass the title value to the function as well, but then you're really better off just doing the inline version all the way and skipping the function. 当然,正如格兰特建议的那样,你也可以将标题值传递给函数,但是你最好只是一直使用内联版本并跳过函数。

Get rid of the BR tag inside your SCRIPT element, and rewrite the tool function to: 摆脱SCRIPT元素中的BR标记,并将工具函数重写为:

function tool(){
    document.getElementsByName("link")[0].title = "after click";
}

and it will work. 它会起作用。 However, it is not the optimal way. 但是,这不是最佳方式。 If you assign an id parameter to the field you can at least use document.getElementById(..), or even better, use a library like jQuery. 如果为字段分配id参数,至少可以使用document.getElementById(..),甚至更好,使用像jQuery这样的库。

使用jquery,您可以编写以下命令:

$("a#link").attr("title","after click");

You can use setAttribute(attributeName, value) on the element that you want to change. 您可以对要更改的元素使用setAttribute(attributeName,value)。

document.getElementById('link').setAttribute('title', 'after click');

This also works for custom attributes 这也适用于自定义属性

document.getElementsByName("link").title = "after click";

Correcting to Jason code: 更正Jason代码:

write document.getElementById("link").title insteadof document.getElementsByName("link").title. write document.getElementById(“link”)。title titleof document.getElementsByName(“link”)。title。

I have tested it on IE7 and Firefox 3. 我在IE7和Firefox 3上测试过它。

<html>
<head>
    <script>
            function tool(){
                    document.getElementById("link").title = "after click";
            }
    </script>
</head>
<body>
    <a href="javascript:tool()" id="link" title="before click">
            click here
    </a>
</body>
</html> 

You can also explore this article for creating nice tooltip using javascript: http ://devirtu.com/2008/08/14/how-to-make-tooltip-with-javascript/ 您还可以使用javascript浏览本文以创建漂亮的工具提示:http://devirtu.com/2008/08/14/how-to-make-tooltip-with-javascript/

I am tackling 2 issues here: 我在这里处理2个问题:

  1. Title is changed when mouse over, but not in the code: 鼠标悬停时标题会更改,但代码中不会更改:
    ... ...
    < a class="a" href="#" name="home" title="Home">Home <a class =“a”href =“#”name =“home”title =“Home”> Home
    ... ...
    document.getElementsByName("home")[0].title = "Title changed"; document.getElementsByName(“home”)[0] .title =“标题已更改”; // working //工作

  2. How to change the class of the link: 如何更改链接的类:

    FROM: < a class="a" href="#" name="home" title="Home">Home FROM:<a class =“a”href =“#”name =“home”title =“Home”> Home
    TO: < a class="current" href="#" name="home" title="Home">Home TO:<a class =“current”href =“#”name =“home”title =“Home”> Home
    document.getElementsByName("home")[0].class = "current"; document.getElementsByName(“home”)[0] .class =“current”; // not working //不工作

    Thanks! 谢谢!

The title has changed, but only in generated code. 标题已更改,但仅在生成的代码中。 This is how JS works - it tackles only with presentation. 这就是JS的工作方式 - 它只能通过演示解决。 Try to use Webdeveloper toolbar for Firefox because it has the option to show generated code along with the original one. 尝试使用Firefox的Webdeveloper工具栏,因为它可以选择显示生成的代码和原始代码。 If you need any other way, think of using some server-side programming. 如果您需要任何其他方式,请考虑使用一些服务器端编程。

My observations: 我的观察:

  • Never mix JS with HTML. 切勿将JS与HTML混合使用。 If you need to update your code, it'll be much easier - search for "unobtrusive JS" to get a better grasp on the issue. 如果你需要更新你的代码,它会更容易 - 搜索“不显眼的JS”以更好地掌握这个问题。 <a href="javascript:..."> or <a href="#" onclick="..."> is therefore a bad coding practise. <a href="javascript:..."><a href="#" onclick="...">是一种糟糕的编码习惯。

  • Do not use large JS packages like JQuery for simple tasks. 不要像JQuery那样使用大型JS包来完成简单的任务。 They're good only if used with their full potential. 只有充分发挥其潜力,它们才是好的。

  • Do you really need to perform HTML manipulation on the fly and why? 你真的需要动态执行HTML操作吗?为什么? Is title tooltip that important to your code? 标题工具提示对您的代码很重要吗? Who should benefit from it: end users or admin? 谁应该从中受益:最终用户还是管理员? What about accessibility? 可访问性怎么样?

  • INFO on the first code block: 第一个代码块的INFO:

  • If we don't know what link to use, we have to collect all of them 如果我们不知道要使用哪个链接,我们必须收集所有这些链接
  • and then test the collection against onclick event 然后针对onclick事件测试集合
  • Suggestions: 建议:
    • use a better event handler ;) 使用更好的事件处理程序;)
    • collect links only from particular part of the page (main or navigation div) to improve speed 仅从页面的​​特定部分(主要或导航div)收集链接以提高速度
  • CAVEATS: 注意事项:
  • this may slow page rendering 这可能会降低页面渲染速度
  • title attribute is hardcoded and same for all links title属性是硬编码的,所有链接都相同


function changeTitle1(){
// find the array of links inside the document
var a = document.getElementsByTagName('a');
// test the array against onclick event
for (var i = 0, j = a.length; i 
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
    • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:
  • INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:

<style type="text/css" media="screen">
    #home #current-home a,
    #contact #current-contact a,
    #about #current-about a
    {/* declarations to style the current state */}
</style>
</head>
<body id="home"> <!-- OR body id="contact" OR body id="about" -->
    <a href="#" title="Home" class="current-home">Home</a>
    <a href="#" title="Contact" class="current-contact">Contact</a>
    <a href="#" title="About us" class="current-about">About us</a>
 INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version: 

INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:

INFO on the second code block: We know exactly what link to check Suggestion: use a better event handler ;) CAVEATS: this can only be used on a single element title attribute is hardcoded and same for all links function changeTitle2(){ // find the link var a = document.getElementById('action_link'); // onclick event a.onclick = function() { try{ // change title value this.title = 'This unique click happened as well!'; // or use setAttribute() method like this /* this.setAttribute('title', 'This unique click happened as well!'); */ // disable default link action return false; } // clear memory leaks with try-finally block finally{a = null;} } } window.onload = function() { changeTitle1(); //changeTitle2(); } @spiro: Regarding your second question about links current state and changing their CSS... well, use CSS :) Short version:

 <style type="text/css" media="screen"> #home #current-home a, #contact #current-contact a, #about #current-about a {/* declarations to style the current state */} </style> </head> <body id="home"> <!-- OR body id="contact" OR body id="about" --> <a href="#" title="Home" class="current-home">Home</a> <a href="#" title="Contact" class="current-contact">Contact</a> <a href="#" title="About us" class="current-about">About us</a> 

Long version: http://www.456bereastreet.com/archive/200503/setting_the_current_menu_state_with_css/ (read the comments as well) 长版: http//www.456bereastreet.com/archive/200503/setting_the_current_menu_state_with_css/ (同时阅读评论)

Note: is it necessary to display the link if you're already on the current page? 注意:如果您已经在当前页面上,是否有必要显示链接

I would use http://jquery.com/ download it and add a script reference to it 我会使用http://jquery.com/下载它并添加一个脚本引用

Give your a tag an id such as myLink 为你的标签添加一个id,例如myLink

Then using JQuery you can write 然后使用JQuery你可以写

$(document).ready(function () {

    $("#myLink").click(function(){

        $("#myLink").attr("title","after click");

    });

});

As waxwing suggests, it's better to use getElementById() 正如waxwing建议的那样,最好使用getElementById()

<a id="aLink" href="http://www.bla.com" title="hello">link</a>
 <script>

function tool(){
document.getElementById('aLink').title = "after click";
}

</script>

Two things are wrong with your supplied code: 您提供的代码有两个问题:

  • As the name implies, documentent.getElementById looks things up by ID, not name. 顾名思义,documentent.getElementById按ID查找内容,而不是名称。 You'll need to supply an ID in that anchor tag. 您需要在该锚标记中提供ID。 Change your link to <a href="javascript:tool()" id="link" name="link" title="before click">click here</a> 将您的链接更改为<a href="javascript:tool()" id="link" name="link" title="before click">click here</a>

  • You're feeding documentent.getElementById the contents of a variable called "link", which presumably doesn't exist. 你正在向documentent.getElementById提供一个名为“link”的变量的内容,这个变量可能不存在。 You actually wanted to pass a literal string, which needs quotes. 你实际上想要传递一个需要引号的文字字符串。 Change that call to document.getElementById("link").title = "after click"; 将该调用更改为document.getElementById("link").title = "after click";

Putting it all together, here's what your code would look like: 总而言之,这就是您的代码的样子:

<html>
<head>
    <script>
        function tool(){
            document.getElementById("link").title = "after click";
        }
    </script>
</head>
<body>
    <a href="javascript:tool()" id="link" name="link" title="before click">
        click here
    </a>
</body>
</html>
<html>
<head>
<script>
window.onload = function () {
    window.document.getElementById("link").onclick = function () {
        this.title = "after click";
        return false;
    };
};
</script>
</head>
<body>
    <a href="http://www.example.com" id="link" title="before click">Click Here</a>
</body>
</html>

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

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