向标签系列添加文本

Add text to series of labels

我有一个字段列表,其中的描述在标签标签内。 我想在每个标签前添加文本 "Your"。

到目前为止我有

<div id="field1">
    <label> First Label </label>
</div>
<div id="field2">
    <label> Second Label </label>
</div>
<div id="field3">
    <label> Third Label </label>
</div>
<div id="field4">
    <label> Fourth Label </label>
</div>
var label = $("label");
$("label").html("Your"+ label.text);

https://jsfiddle.net/smftmdf1/1/

有什么方法可以不使用 类 或 ID 来实现这一点?

您当前的代码不起作用,因为您提供了对 text 的引用,而不是使用 "Your"+ label.text() 执行函数本身。但请注意,这只会将所有 label 元素设置为相同的值。

要执行您需要的操作,您可以向 text() 提供一个函数。此函数将接收当前 text 值作为第二个参数。因此,您只需将 Your 附加到该值即可。试试这个:

$('label').text(function(i, v) {
    return 'Your ' + v;
});

Example fiddle

text() 代替 html 试试 each()。我还在选择器中使用了 [id*="field"] 标识符,因此它仅适用于具有 fieldx id.

的 div 内的标签

$('[id*="field"] label').each(function(){
  $(this).text('Your '+ $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="field1">
    <label> First Label </label>
</div>
<div id="field2">
    <label> Second Label </label>
</div>
<div id="field3">
    <label> Third Label </label>
</div>

使用.html( function )

function Type: Function( Integer index, htmlString oldhtml ) => htmlString A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

$("label").html(function(i,v) { 
 return 'Your ' + v;
});

Fiddle

您需要使用每个 Jquery 函数来获得所需的结果。

var label = $("label");
$("label").each(function () {
    $(this).html("Your" + $(this).text())
});

解决方法: https://jsfiddle.net/7g7ycqnu/

试试 .prepend()

$('label').prepend('Your');

这是相当简短和富有表现力的+照顾 html 如果有的话。

DEMO

对于您的实际标记,有一个简单的方法可以在不使用 类、id 或 jquery 开销的情况下执行此操作。

var labels = document.getElementsByTagName('label');
//OR: var labels = document.querySelectorAll('label');
for (var i = 0; i < labels.length; i++) {
    labels[i].textContent = 'Your' + labels[i].textContent;
    //OR: labels[i].innerHTML = 'Your' + labels[i].innerHTML;
}

另外,考虑到按标签名称批量选择不是最佳做法,并且根据您的文档结构,它可能会导致不需要的替换。如果您希望标签内有其他标签(您希望保留),请使用 innerHTML 属性.