jquery:将标签的标题设置为"为" - 属性

时间:2015-12-09 10:41:57

标签: jquery label attr

这是我的代码:

$(document).ready(function(){
  $("label").attr({
    title: getTitle($(this).attr('for')),
    className: "something" 
  });

  function getTitle(val) {
    return "blubb "+val;
  }
});

函数getTitle(val)给了我回复" blubb undefined"而不是" blubb contact_properties_list_18"。可能是什么问题?

<label class="something" for="contact_properties_list_18" title="blubb undefined">Sonstige</label>

1 个答案:

答案 0 :(得分:0)

this您使用它的地方并未引用该标签。 jQuery没有说thisready处理程序中的内容。

您可以使用接受函数的attr版本:

$("label").attr("title", function() {
    this.className = "something";
    return getTitleFor(this.htmlFor);
});

&#13;
&#13;
$("label").attr("title", function() {
    this.className = "something";
    return this.htmlFor;
});
&#13;
.something {
  color: green;
}
&#13;
<label for="foo">foo</label>
<label for="bar">bar</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

...但是既然你做了两件事,我可能会使用each

$("label").each(function() {
    this.title = getTitleFor(this.htmlFor);
    this.className = "something";
});

&#13;
&#13;
$("label").each(function() {
    this.title = this.htmlFor;
    this.className = "something";
});
&#13;
.something {
  color: green;
}
&#13;
<label for="foo">foo</label>
<label for="bar">bar</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

请注意,我使用htmlFor只是为了避免不必要地创建jQuery实例。 htmlFor反映了for属性(具有通用浏览器支持)。类似地,DOM元素上的title属性反映了title属性,因此分配给它也可以。