Sgn*_*gn. 5 jquery greasemonkey
我正在尝试写一个Greasemonkey脚本.网页上有这样的内容:
<div id="div1" class="..." title="
asdsadsadasd <e;...
">...</div>
Run Code Online (Sandbox Code Playgroud)
我想用jQuery attr方法获得它的标题.但它返回一个空值.我的js代码是这样的:
$("#div1").attr("title");
Run Code Online (Sandbox Code Playgroud)
我已经尝试过许多不同的方式警报,我确信正确选择了所需的元素,所有其他属性都没问题!只是这一个返回空字符串!('')它与多线有关吗?
更多细节: 我使用的是最新的jQuery(1.8.2),我的浏览器是Firefox 16.0.1.我看到了这个链接,它在那里工作!也许这是因为别的东西.实际上我正在使用Greasemonkey脚本进行编码,该脚本正在改变我不能编辑的网页.因此无法编辑HTML代码.
title不是div的有效属性,但应该仍然有效.如果你可以轻松更改html,你可以使用:
<div id="div1" class="..." data-title="
asdsadsadasd <e;...
">...</div>
Run Code Online (Sandbox Code Playgroud)
JS
alert( $("#div1").data("title"));
Run Code Online (Sandbox Code Playgroud)
还要确保包装代码,document.ready因此代码触发时元素存在.我怀疑这可能是你的问题
$(function(){
/* your code*/
})
Run Code Online (Sandbox Code Playgroud)
是title空白的,因为它(或者很可能是<div>)是在 Greasemonkey 脚本触发后通过 AJAX 添加的。
使用waitForKeyElements() 实用程序来处理这种情况。
这是一个使用 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);
Run Code Online (Sandbox Code Playgroud)