【问题标题】:How to set a label's title based on it's inner HTML?如何根据标签的内部 HTML 设置标签的标题?
【发布时间】:2014-02-10 21:23:01
【问题描述】:

我有一个带有很多复选框的 html 表单域。

如何根据标签的内部 HTML 设置标签的标题属性?我需要为所有标题执行此操作。

比如我需要改造

<div id=field>
  <label class='option'>Ski</label>
  <label class='option'>Hockey</label>
  <label class='option'>Baseball</label>
</div>

到:

<div id=field>
  <label title='Ski' class='option'>Ski</label>
  <label title='Hockey' class='option'>Hockey</label>
  <label title='Baseball' class='option'>Baseball</label>
</div>

我尝试了以下 jQuery 代码:

$('#field label.option').attr('title',$(this).html());  

但它给了我很多垃圾。

那么如何获取每个匹配标签内的值呢?

这是 jQuery 1.4.4。

请指教。

【问题讨论】:

  • 你能把你的html贴出来吗?
  • 为什么不使用带有 id 的 div
  • @atom217 - 我愿意。实际的 HTML 要复杂得多,这只是一个简化版本。

标签: jquery jquery-1.5


【解决方案1】:
$('#field label.option').attr('title',function(){ return $(this).text() });

【讨论】:

    【解决方案2】:

    title 属性应该只包含文本,所以你最好给用户text()

    $('#field label.option').prop('title', function() { return $(this).text(); });
    

    如果您绝对title 设置为内部HTML,请使用html()

    $('#field label.option').prop('title', function() { return $(this).html(); });
    

    jsFiddle Demo

    【讨论】:

    • 是的,标题包含文字。
    • 我使用 jquery 1.4.4。并且 prop 方法仅在 1.6 版本中添加
    • 好的,只需将prop() 替换为attr()
    【解决方案3】:

    这可能对你有帮助

    $('.option').each(function(i,lbl)
       {
           $(lbl).attr('title',$(this).html());
       }
    );
    

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多