获取这个锚标题文本jQuery

get this anchor title text jQuery

本文关键字:文本 jQuery 标题 获取      更新时间:2023-09-26

我正在尝试将所有锚标题文本放入儿童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中获取文本

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

:

<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/

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

现场演示

<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类,我从这里的答案中获取。

带有工具提示自定义样式的实时演示

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

先关闭你的标签。

<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 );
     }); 
  }