0

I have a link. Like this:

<a href="#" title="Title from this link"></a>

I want remove this title and put the title text in a data attribute. As data-title. How can i make this with jquery. So remove the title element. And place the text of the title element. In a new title data element.

Thanks

4

6 回答 6

5
// you'd probably wanna give an unique id to your anchor to more easily identify it
var anchor = $('a'); 
var title = anchor.attr('title');
anchor.removeAttr('title');
anchor.attr('data-title', title);
于 2013-02-20T07:50:09.670 回答
1
// set title data-title to value of title
$("a").attr("data-title", $("a").attr("title"))
// clear title
$("a").attr("title", "");

另外我会给你的链接一个class,所以这个动作不会a在整个页面上运行。

于 2013-02-20T07:49:36.110 回答
1

设置元素属性的用户attr方法。以及removeAttr删除属性的方法

 $("a").attr("data-title", $("a").attr("title"));
 $("a").attr("title", ""); 
 // or
 $("a").removeAttr("title"); 

PS:会为锚元素建议一个唯一的 id 或一个类

于 2013-02-20T07:51:28.497 回答
1

尝试:

$("a").attr("data-title", $("a").attr("title"));
$("a").removeAttr("title");
于 2013-02-20T07:51:35.357 回答
0

jsfiddle 链接:http: //jsfiddle.net/NEBh4/

您可以使用 firebug 或任何其他开发工具查看结果窗口中的链接发生的更改

$(document).ready(function(){
//example code one
var tempLink = $('#link');//cash the jquery object for performance
tempLink.attr('data-title', tempLink.attr('title')).removeAttr('title');

/*In above example I used an id to capture the html element, which mean u can only do above step only for one element. If you want to apply above step for many links you can use the following code. In this case I'm using a class name for the link element*/

//example code two
$('.link').each(function(){
    $(this).attr('data-title', $(this).attr('title')).removeAttr('title');
});

});

上述示例的 HTML

<!-- for example code one -->
<a id="link" class="link" href="#" title="Title from this link"></a>

<!-- for example code two -->
<a class="link" href="#" title="Title from this link 1"></a>
<a class="link" href="#" title="Title from this link 2"></a>
<a class="link" href="#" title="Title from this link 3"></a>
于 2013-02-20T08:02:04.950 回答
0
<a id="1" href="#" title="Title from this link 1"></a>
<a id="2" href="#" title="Title from this link 2"></a>

var t = $("a[title='Title from this link 1']").attr("title");
$("#2").attr("title", t);
于 2013-02-20T07:54:30.023 回答