0
<div class="item" onclick="location.href='a1.html'"></div>
<div class="item" onclick="location.href='a2.html'"></div>
<div class="item" onclick="location.href='a3.html'"></div>
<div class="item" onclick="location.href='a4.html'"></div>
<div class="item" onclick="location.href='a5.html'"></div>

$('.item').each(function() {
    $(this)[0].replace('div', 'a')
})

divすべてのタグをタグに変更することはできaますか? 上記のコードを試しましたが、うまくいきません。何かアイデアはありますか?

ありがとう

4

4 に答える 4

2

試す

$('.item').each(function(){
    var $this = $(this);
    var onclick = $this.attr('onclick');
    var match = onclick.match(/(location.href=')(.*)(')/);
    $this.replaceWith($('<a/>', {href : match[2], html: this.innerHTML}))
})

デモ:フィドル

于 2013-06-08T04:19:20.920 に答える
2

同様にショットを撮る:

$('.item').each(function() {
    $(this).replaceWith(
        $('<a>', {
            href: /'(.+)'/.exec($(this).attr('onclick'))[1],
            append: $(this).contents()
        })
    );
});

デモ

説明:

  • アンカー要素 ( <a>) を作成します。
    • hrefdiv のonclick属性の単一引用符の間のテキストに設定します。
    • すべてのコンテンツ (子孫要素とテキスト ノード) を div からアンカー要素に移動します。これにより、関連付けられたイベント ハンドラーが保持されます。
  • div を作成されたアンカー要素に置き換えます。

div意味:以前に (.on()またはを介し​​て)直接バインドされたハンドラーaddEventListenerは引き続き破棄されます。

于 2013-06-08T04:20:36.290 に答える
0

試す:

<div class="item" onclick="location.href='a1.html'"></div>
<div class="item" onclick="location.href='a2.html'"></div>
<div class="item" onclick="location.href='a3.html'"></div>
<div class="item" onclick="location.href='a4.html'"></div>
<div class="item" onclick="location.href='a5.html'"></div>

$('.item').each(function(){
    var onClick = $(this).attr('onclick');
    $(this).replaceWith('<a class="item" onclick="'+onClick+'"></a>');
});
于 2013-06-08T04:15:42.377 に答える
0

このリンクを参照してください。あなたの例では、次のようにします。

$('.item').each(function() {
    $(this).replaceWith($('<a>' + this.innerHTML + '</a>'));
})
于 2013-06-08T04:06:07.937 に答える