2016-11-07 65 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>