![](/img/trans.png)
[英]String.Replace only replaces first occurrence of matched string. How to replace *all* occurrences?
[英]How to use String.replace() to replace ALL occurrences of a pattern
在許多div中,我必須通過用句點替換空格來改變類名....
所以我嘗試了這個
$(jqueryElements).each(function(index)
{
jqueryElements[index].className.replace(' ','.');
});
當班級有兩個單詞時,它可以正常工作......但是當班級名稱有3個或更多單詞時,它就會失敗......
className='one word';
jqueryElement[index].className.replace(' ','.'); // console-> one.word
className='many many words';
jqueryElement[index].className.replace(' ','.'); // console-> many.many words
有什么不對?
我正在使用Chrome 25,Win7,jQuery 1.8
編輯2
我需要替換空格來搜索具有特定類名的所有span元素。
所以我用這種方式使用jquery ......
$('#span-container').find('span.'+jqueryElements[index].className.replace(' ','.').text('there are '+span_counter+'spans with this classname');
這個請求的結果應該是:
$('#span-container').find('span.many.many.words).text('there are '+span_counter+'spans with this classname');
相反,我有:
$('#span-container').find('span.many.many words).text('there are '+span_counter+'spans with this classname');
請改用.replace(/ /g, '.')
。 g
表示全局(如“全局替換”)。 雖然我對你想要做的事情有點嗤之以鼻。
不要使用替換,使用split
和join
:
jqueryElements[index].className.split(' ').join('.');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.