如何获取div元素的title属性?

时间:2012-10-21 21:19:59

标签: jquery greasemonkey

我正在尝试编写Greasemonkey脚本。在网页上有类似的内容:

<div id="div1" class="..." title="
  asdsadsadasd&nbsp;&lte;...
">...</div>

我想使用jQuery attr方法获取其标题。但它返回一个空值。我的js代码是这样的:

$("#div1").attr("title");

我已经尝试过许多不同的方式警报,我确信正确选择了所需的元素,所有其他属性都没问题!只是这一个返回空字符串! ('')它与多线有关吗?

更多详情: 我正在使用最新的jQuery(1.8.2),我的浏览器是Firefox 16.0.1。 我看到了this link,它在那里工作了!也许这是因为别的东西。实际上我正在使用Greasemonkey脚本进行编码,该脚本正在改变我不能编辑的网页。因此,无法编辑HTML代码。

5 个答案:

答案 0 :(得分:7)

title不是div的有效属性,但仍应有效。如果您可以轻松更改html,可以使用:

<div id="div1" class="..." data-title="
  asdsadsadasd&nbsp;&lte;...
">...</div>

JS

alert( $("#div1").data("title"));

还要确保在document.ready中包装代码,以便在代码触发时存在元素。我怀疑这可能是你的问题

$(function(){
/* your code*/

})

答案 1 :(得分:1)

问题可能与jquery版本有关。

它与Jquery.1.8.2一起运行。成功。 我尝试使用chrome和ie9。

<强> http://jsfiddle.net/LgkhW/2/

答案 2 :(得分:1)

title为空,因为在Greasemonkey脚本触发后,它(或很可能是<div>)是通过AJAX添加的。

使用the waitForKeyElements() utility来处理这种情况。

这是 完整脚本 ,它使用jQuery和waitForKeyElements来获取该标题:

// ==UserScript==
// @name     _Grab element's title, when it is added by AJAX
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle   
// ==/UserScript==
/*- The @grant directive is needed to work around a design change introduced
    in GM 1.0.   It restores the sandbox.
*/

function grabDivTitle (jNode) {
    //***** YOUR CODE HERE *****
    var titleStr    = jNode.attr ("title");
    console.log ("Title is:", titleStr);
}

waitForKeyElements ("#div1", grabDivTitle);

答案 3 :(得分:1)

我有一个类似的问题,但似乎jquery ui工具提示功能导致了这个问题。我最终在与jquery ui无关的元素中添加了另一个属性。我使用了alt元素,但是如果你已经使用了它,你可以使用data-alt。

之类的东西
<a class="tooltip" 
    title="this will show up in the tooltip and may cause trouble using title later on" 
    data-alt="Grab this attribute instead of the title to bypass jqui showing the title attr as an empty string"
/>
<script>
    $(".tooltip").tooltip();
    a.click(function(){
        var title = $(this).attr('title'); // this showed up as an empty string
        title = $(this).attr('data-alt'); // this showed up as the text I was expecting
    });
</script>

答案 4 :(得分:0)

看起来像个错误:

&#13;
&#13;
$("<div>").attr("tilte","dyanmic").addClass("test").appendTo("body");
alert($("#div1").attr("title"));
alert($(".test").attr("title"));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="..." title="static">...</div>
&#13;
&#13;
&#13;