【问题标题】:get this anchor title text jQuery获取这个锚标题文本jQuery
【发布时间】:2015-06-02 05:44:36
【问题描述】:

我正在尝试获取子 div 中的所有锚标题文本

我的 HTML

<div onClick="openList();">
  <div class="inc">
    <div class="iWrap">
        <a title="<div>blah1 blah1</div>"></a>
        <a title="<div>blah2 blah2</div>"></a>
        <a title="<div>blah3 blah3</div>"></a>
        <a title="<div>blah4 blah4</div>"></a>
    </div>
  </div>
</div>

<div onClick="openList();">
  <div class="inc">
    <div class="iWrap">
        <a title="<div>some text 1</div>"></a>
        <a title="<div>some text 2</div>"></a>
        <a title="<div>some text 3</div>"></a>
        <a title="<div>some text 4</div>"></a>
    </div>
  </div>
</div>

我的 jQuery 代码

function openList()
{
    var getTitletxt = $(this).find('a').attr("title");
    console.log(getTitletxt);
}

我在 console.log 中收到 undefined。基本上我正在尝试在标题 div 中获取文本。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

不要使用内联事件处理程序。您可以使用on 来绑定事件。

HTML

<div class="myClass">
<!--       ^^^^^^^^^ -->
    <div class="inc">
        <div class="iWrap"> <a title="<div>blah1 blah1</div>">a</a>
            <a title="<div>blah2 blah2</div>">b</a>
            <a title="<div>blah3 blah3</div>">c</a>
            <a title="<div>blah4 blah4</div>">d</a>
        </div>
    </div>
</div>

<div class="myClass">
<!--     ^^^^^^^^^ -->
    <div class="inc">
        <div class="iWrap"> <a title="<div>some text 1</div>">aa</a>
            <a title="<div>some text 2</div>">bb</a>
            <a title="<div>some text 3</div>">cc</a>
            <a title="<div>some text 4</div>">dd</a>
        </div>
    </div>
</div>

Javascript

$('.myClass').on('click', 'a', function() {
    alert($(this).attr('title'));
});

演示:http://jsfiddle.net/tusharj/zfboe9o1/

【讨论】:

    【解决方案2】:

    使用this 传递当前对象,默认情况下,这不适用于绑定处理程序使用javascript 内联处理程序。您的标题也无效,您可能需要未包含在 div 中的文本。

    Live Demo

    <div onClick="openList(this);">
    
    function openList(obj)
    {
        var getTitletxt = $(obj).find('a').attr("title");
        console.log(getTitletxt );
    }
    

    改变

    <a title="<div>some text 1</div>"</a>
    

    <a title="some text 1"> anchor 1 </a>
    

    对于自定义工具提示类,您可以制作 css 类,我从答案 here 中获取。

    Live demo with tool tip custom style

    a.ac[title]:hover:after 
    {
    }
    

    【讨论】:

    • 感谢这项工作。 .但我的标题需要自定义 css.. 所以标题中的 div 标签.. 效果很好。
    【解决方案3】:

    首先关闭你的标签。

    <a title="<div>some text 1</div>"> </a>
    

    在函数中传递this作为参数

      <div onClick="openList(this);">
    
       function openList($this)   
       {
         $($this).find('a').each(function(){  // To get all <a> tag title
            var getTitletxt = $(this).attr("title");
            console.log(getTitletxt );
         }); 
      }
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多