【发布时间】:2012-09-12 04:43:45
【问题描述】:
好的,这就是交易:我正在尝试创建一个用户脚本,以在 Greasemonkey/Chrome/人们用来管理这些事情的任何其他工具中使用。我想做的一部分是为我为这个特定脚本设计的图标创建标签。我至少对如何在 Jquery 中完成此任务有一个粗略的了解。我会使用的代码是这样的:
$('li.tab.iconic').each(function (i) {
var spanName = $('this').attr(id);
var toRemove = '_button';
var spanNameCrop = spanName.replace(toRemove,'');
$('this').append('<span class="tooltip_label">'+spanNameCrop+'</span>');
});
基本上,我想获取每个li 的id 属性,从中修剪短语“_button”,并将剩余的文本插入将成为标签的跨度中。我的问题是我搜索了高低,但没有找到关于如何在 javascript 中执行这样的循环的明确说明。有可能吗?
另外,我正在设计的网站确实包含 Jquery 库。有没有办法告诉我的脚本在站点加载 jquery 后加载,以便 jquery 脚本可以工作?
编辑:感谢 Avladov。这是最终的脚本。
var jQuery, $ = null;
function addJQuery(callback) {
var p = null;
if(window.opera || window.navigator.vendor.match(/Google/)) {
var div = document.createElement("div");
div.setAttribute("onclick", "return window;");
p = div.onclick();
}
else {
p = unsafeWindow;
}
jQuery = $ = p.jQuery.noConflict();
callback();
}
var myFunction = function() {
jQuery('#header .tab.iconic[id!="missinge_button"] a').css({"background-image":"url('http://i.imgur.com/2QmZG.png')"});
jQuery('#header .tab.iconic').each(function (i) {
var tabID = jQuery(this).attr('id');
var labelName = tabID.replace('_button','');
if (jQuery(this).find('span[class="tooltip_label"]').length){
}
else{
jQuery(this).append('<span class="tooltip_label">'+labelName+'</span>');
jQuery('.tooltip_label').css({'text-transform':'capitalize'});
}
});
};
addJQuery(myFunction);
【问题讨论】:
-
您不应该为
this对象使用引号。将它们用于id属性$(this).attr('id'); -
我不记得我是否需要
this的引号。固定。 -
您不需要 $(document).ready 在greasemonkey 脚本中。当 GM 脚本开始执行时,文档已经完全加载。
标签: javascript jquery userscripts