リンクがあります。このような:
<a href="#" title="Title from this link"></a>
このタイトルを削除して、タイトルテキストをデータ属性に入れたいと思います。データタイトルとして。jqueryでこれを作成するにはどうすればよいですか?したがって、title要素を削除します。そして、title要素のテキストを配置します。新しいタイトルデータ要素内。
ありがとう
リンクがあります。このような:
<a href="#" title="Title from this link"></a>
このタイトルを削除して、タイトルテキストをデータ属性に入れたいと思います。データタイトルとして。jqueryでこれを作成するにはどうすればよいですか?したがって、title要素を削除します。そして、title要素のテキストを配置します。新しいタイトルデータ要素内。
ありがとう
// 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);
// set title data-title to value of title
$("a").attr("data-title", $("a").attr("title"))
// clear title
$("a").attr("title", "");
また、私はあなたのリンクにを与えるclass
ので、このアクションはa
ページ全体のすべてで実行されるわけではありません。
attr
要素の属性を設定するユーザーメソッド。そしてremoveAttr
、属性を削除するメソッド
$("a").attr("data-title", $("a").attr("title"));
$("a").attr("title", "");
// or
$("a").removeAttr("title");
PS:アンカー要素の一意のIDまたはクラスを提案します
試す:
$("a").attr("data-title", $("a").attr("title"));
$("a").removeAttr("title");
<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);
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>