我有一个无法直接更改的 html 代码。
<span class="class1 class2 class3 "> First name*: </span>
我需要移动开头或文本处的*。最终结果应该是这样的:
<span class="class1 class2 class3 "> *First name: </span>
我还需要将 * 设为红色(我需要仅为该 Angular 色添加一个类)。
有什么想法吗?
最佳答案
我建议:
$('span.class1.class2.class3').text(function(i, t){
/* i is in the index of the current element among those returned,
t is the text of the current element.
We return the new text, which is an asterisk, followed by the original text,
with the asterisk removed (using replace to replace the asterisk with an empty string):
*/
return '*' + t.replace(/\*/,'');
});
但是,如果您需要更通用的方法(例如,如果您有多个具有相同/相似选择器的元素):
// selects all the span elements, and filters:
$('span').filter(function(){
// discards the elements that *don't* have '*:' in their text:
return $(this).text().indexOf('*:') > -1;
// iterates over those elements (as above):
}).text(function(i, t) {
return '*' + t.replace(/\*/,'');
});
为了“使其变成红色”,您必须操作元素的 HTML,而不仅仅是文本:
$('span').filter(function(){
return $(this).text().indexOf('*:') > -1;
// Using 'html()' to set the HTML of the 'span' element:
}).html(function(i, h) {
// creating a span and prepending to the current element
return '<span class="required">*</span>' + h.replace(/\*/,'');
});
与 CSS 结合:
.required {
color: red;
}
此外,为了简单起见,假设您希望使用类名来定位 *
(因此将其包装在元素节点中),您可以避免字符串操作,只需 float
:
$('span').html(function(i,h){
// simply wrapping the `*` in a span (using html() again):
return h.replace(/(\*)/,'<span class="required">*</span>');
});
使用 CSS:
.required {
float: left;
color: red;
}
引用文献:
关于javascript - jQuery:如何在字母之前移动字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17009906/