2013-02-20 194 views
0

我有一個鏈接。像這樣:添加數據元素到元素

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

我想刪除此標題並將標題文本置於數據屬性中。作爲數據標題。我如何使這與jQuery。 因此刪除標題元素。並放置標題元素的文本。在新的標題數據元素中。

感謝

+1

請顯示輸出示例 – 2013-02-20 07:47:54

回答

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); 
1
// set title data-title to value of title 
$("a").attr("data-title", $("a").attr("title")) 
// clear title 
$("a").attr("title", ""); 

另外我想給你的鏈接class,所以這個動作並非任何a整個頁面上運行。

1

用戶attr設置元素屬性的方法。而removeAttr方法來刪除屬性

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

PS:建議一個唯一的ID或錨元素

1

嘗試類:

$("a").attr("data-title", $("a").attr("title")); 
$("a").removeAttr("title"); 
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); 
0

的jsfiddle鏈接:http://jsfiddle.net/NEBh4/

喲您可以使用螢火蟲或任何其他開發工具查看結果窗口中的鏈接發生的變化

$(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>