2016-11-07 61 views
0

出於某種原因,Javascript replace('search', 'replace')函數適用於某些HTML實體字符串作爲搜索字詞,但其他字詞則不如我所期望的那樣。這些不一致是非常有問題的,我甚至無法用它的工作方式解決這個問題。我怎樣才能保證這些實體搜索術語總能找到完整的明文單詞?我需要替換的工作方式‐確實在這個例子:Javascript替換()使用html實體

$(document).ready(function(){ 
 
    $('#good').html($('#good').html().replace($('#good').data('text'), 'FOUND')); 
 
    $('#okay').html($('#okay').html().replace($('#okay').data('text'), 'FOUND')); 
 
    $('#bad').html($('#bad').html().replace($('#bad').data('text'), 'FOUND')); 
 
    $('#wrong').html($('#wrong').html().replace($('#wrong').data('text'), 'FOUND')); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id="good" data-text="find"> 
 
1: find 
 
</div> 
 
<div id="okay" data-text="&dash;"> 
 
2: &dash; 
 
</div> 
 
<div id="bad" data-text="&gt;"> 
 
3: &gt; 
 
</div> 
 
<div id="wrong" data-text="&amp;"> 
 
4: &amp; 
 
</div>

+4

你有沒有嘗試過的''而不是html的()''的.text()? – vlaz

+0

你有什麼不一致? –

+1

試過你用@vlaz建議用'.text()'替換'.html()'。完美的作品... – War10ck

回答

1

使用.text()代替.html(),作爲@vlaz建議。我跑使用.text()的例子,它工作得很好:

$(document).ready(function(){ 
 
    $('#good').text($('#good').text().replace($('#good').data('text'), 'FOUND')); 
 
    $('#okay').text($('#okay').text().replace($('#okay').data('text'), 'FOUND')); 
 
    $('#bad').text($('#bad').text().replace($('#bad').data('text'), 'FOUND')); 
 
    $('#wrong').text($('#wrong').text().replace($('#wrong').data('text'), 'FOUND')); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id="good" data-text="find"> 
 
1: find 
 
</div> 
 
<div id="okay" data-text="&dash;"> 
 
2: &dash; 
 
</div> 
 
<div id="bad" data-text="&gt;"> 
 
3: &gt; 
 
</div> 
 
<div id="wrong" data-text="&amp;"> 
 
4: &amp; 
 
</div>