洗掉 % 并繼續使用 jQuery 進行測驗
<div id="top_content">testing %</div> == 0$
我嘗試使用此代碼,但沒有成功
$('.top_content:contains("%: ")').each(function(){
$(this).html($(this).html().split("%: ").join(""));
});
頂部內容是 wordpress 插件中的一個元素
感謝幫助
uj5u.com熱心網友回復:
- 使用選擇器
$('#top_content').(...);按 id 選擇元素 - 重命名或洗掉文本的使用
$(...).replace(...);方法
像這樣:
var new_content = $('#top_content').html().replace(new RegExp(' %','g'), '');
$('#top_content').html(new_content);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top_content">testing %</div>
uj5u.com熱心網友回復:
您的原始代碼不起作用的兩個原因是,首先:因為您選擇了錯誤的元素;該元素有一個id屬性,但您使用的是基于類的選擇器 ( .top_content);并且還因為您試圖將文本字串拆分為字符序列 – "%: "– 該字串中不存在該字串。
雖然這種方法當然可以作業:
$('#top_content:contains("%")').each(function() {
$(this).html($(this).html().split(" %").join(""));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top_content">testing %</div>
通常最好使用該replace()方法來修改文本,因為它將字串替換在一個位置,而不必記住洗掉 (with split()) 然后join()將它們與所需的字符一起洗掉。
下面是一種String.prototype.replace()與 jQuery 一起使用的方法:
// selecting the element(s), and using the
// anonymous function of the text() method
// to update the text; passing in a reference
// the index of the current element in the
// jQuery collection, and a reference to the
// the current text of that element:
$('#top_content').text(function(i,old){
// here we return the modified string, which
// simply takes the existing string and
// replaces the '%' character with an empty
// string, and then removes any leading/
// trailing white-space with
// String.prototype.trim():
return old.replace('%', '').trim();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top_content">testing %</div>
或者,沒有 jQuery:
// we need to reference the textContent of this element
// twice, once to set and once to get; therefore we
// cache a reference to the element (in order to avoid
// querying the DOM multiple times):
let topContent = document.querySelector('#top_content');
// here we set the textContent of the element to the
// value returned by using String.prototype.replace()
// to remove the '%' character and replace it with an
// empty string; and removing leading/trailing white-space
// from the string as above:
topContent.textContent = topContent.textContent.replace('%', '').trim();
<div id="top_content">testing %</div>
參考:
- JavaScript:
String.prototype.replace().String.prototype.split().String.prototype.trim().
- jQuery:
text().
uj5u.com熱心網友回復:
您為 id remove '.' 使用了錯誤的選擇器。并輸入“#”來選擇 ID。而且由于 id 選擇器只回傳元素,沒有整個元素陣列,因此您不能使用回圈函式 (.each)。
否則你所做的一切都是正確的。
$("#top_content").html().split("%").join("")
uj5u.com熱心網友回復:
- 您需要選擇 $('#top_content')。top_content是一個 id 名稱
- 在 contains() 和 split() 函式中定位實際內容
$('#top_content:contains("%")').each(function(){
$(this).html($(this).html().split("%").join(""));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/520019.html
