0

我有一个无法直接更改的 html 代码。

<span class="class1 class2 class3 "> First name*: </span>

我需要在开头或文本处移动 *。最终结果应该是这样的:

<span class="class1 class2 class3 "> *First name: </span>

我还需要将 * 设为红色(我只需要为这个角色添加一个类)。

有任何想法吗?

4

3 回答 3

2

如果问题是您给出的非常具体的场景,

$(".class1.class2.class3").each(function() {
   var inner = $(this).html();
   $(this).html("*" + inner.replace("*",""));
}
于 2013-06-09T13:13:51.060 回答
2

我建议:

$('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(/\*/,'');
});

JS 小提琴演示

但是,如果您需要更通用的方法(例如,如果您有多个元素具有相同/相似的选择器):

// 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(/\*/,'');
});

JS 小提琴演示

为了“使它变红”,您必须操作元素的 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;
}

JS 小提琴演示

此外,为简单起见,假设您希望*使用类名作为目标(因此将其包装在元素节点中),您可以避免字符串操作,并且只需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;
}

JS 小提琴演示

参考:

于 2013-06-09T13:27:17.733 回答
0
var span = $('span.class1.class2.class3');
var new_text = span.text().replace(/\*/, '').replace(/^(\s*)/, '\1<span style="color:red;">*</span>');
span.html(new_text);

Demo

于 2013-06-09T13:19:16.030 回答