javascript - jQuery:如何在字母之前移动字符

标签 javascript jquery

我有一个无法直接更改的 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(/\*/,'');
});

JS Fiddle demo .

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

// 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 Fiddle demo .

为了“使其变成红色”,您必须操作元素的 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 Fiddle demo .

此外,为了简单起见,假设您希望使用类名来定位 * (因此将其包装在元素节点中),您可以避免字符串操作,只需 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 Fiddle demo .

引用文献:

关于javascript - jQuery:如何在字母之前移动字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17009906/

相关文章:

javascript - 深度路由未按预期工作 ui-router

javascript - 与未定义相比,类型错误 - 数据为空

javascript - 在数据表变量中转义单引号

javascript - JQuery TableSorter 单击操作没有效果

javascript - 函数导出未按预期工作

javascript - JSDoc 类型等于数组成员

Javascript 取消焦点选择菜单

javascript - 查找类名为 angularjs 的元素并将类添加到元素

javascript - javascript 中只读的选项,然后禁用复选框属性

javascript - JQuery 表格排序器问题