0

&次のようなものを含む div に動的に出力される URL がいくつかあります。

<div id="box">
    <a href="http://domain.com/index.html&location=1">First URL</a> 
    <a href="http://domain.com/index.html&location=2">Second URL</a>
</div>

出力がこれになるように、 jQueryを使用して&、代わりにのすべてのインスタンスを同等のHTMLエンティティに変換する方法はありますか?

<div id="box">
    <a href="http://domain.com/index.html&amp;location=1">First URL</a> 
    <a href="http://domain.com/index.html&amp;location=2">Second URL</a>
</div>
4

2 に答える 2

2
$('#box a').each(function(){
  $(this).attr('href', $(this).attr('href').replace('&','&amp;'));
  });
于 2012-07-26T01:18:56.913 に答える
2

これにより、ドキュメント内に存在するすべてのタグがループされ、属性内のすべての特殊文字が html エンティティaに置き換えられます。href

$('a').each(function(){
    $(this).attr('href',htmlEncode($(this).attr('href')));
    console.log($(this).attr('href'));
});


function htmlEncode(value){
  return $('<div/>').text(value).html();
}

ワーキングデモ


すべてのタグをループしa、& 記号のみを置き換えます。

$('a').each(function(){
    $(this).attr('href',$(this).attr('href').replace('&','&amp;');
    console.log($(this).attr('href'));
});
于 2012-07-26T01:21:55.943 に答える