gpt4 book ai didi

javascript - 用户脚本中的可重用代码

转载 作者:行者123 更新时间:2023-12-03 08:43:21 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的用户脚本(针对 Greasemonkey/Tampermonkey),但我无法完全让它工作。目标是在页面加载时添加链接,然后在元素的 mouseup() 触发时更改 URL (href)。触发的代码使用声明元素中的新属性,因此需要再次设置它们。

我尝试的主要是将可重用的代码包装在 function run() {/* code */} 中(进行必要的调整以执行正确的操作,无论是在页面加载时调用还是在mouseup),但这会返回一个错误,指出 run() 未定义。如何正确地重用这样的用户脚本中的代码?

$(document).ready(function() {
// REUSABLE CODE
var projI=new OpenLayers.Projection("EPSG:900913");
var projE=new OpenLayers.Projection("EPSG:4326");
var center_lonlat=(/* variable declaration */);
var topleft=(/* variable declaration */);
var bottomright=(/* variable declaration */);
lat=Math.round(center_lonlat.lat * 1000000)/1000000;
lon=Math.round(center_lonlat.lon * 1000000)/1000000;
spn=/* variable declaration */;
});

$(document).ready(function() {
$('div .olControlAttribution').append('<a id="WMEtoGMM" href=" \
/* link here that uses above variables */"'+ \
'target="_blank">Open new page</a>');
});

$('div .view-area.olMap #mouseupElement').mouseup(function() {
$('#WMEtoGMM').attr('href', 'URL HERE');
});

最佳答案

据我了解这个问题,您在文档就绪中有一些代码,您希望在文档就绪后能够按要求运行。

但是,更重要的是,您希望能够使用该可重用函数的结果。

因此,将代码移出到它自己的函数中,该函数返回一个对象并调用该函数,即:

function calc_values() {
// call this function something that makes more sense in the context
// REUSABLE CODE
var obj = {}; // create a new object to store the values
obj.projI=new OpenLayers.Projection("EPSG:900913");
obj.projE=new OpenLayers.Projection("EPSG:4326");
obj.center_lonlat=(/* variable declaration */);
obj.topleft=(/* variable declaration */);
obj.bottomright=(/* variable declaration */);
obj.lat=Math.round(center_lonlat.lat * 1000000)/1000000;
obj.lon=Math.round(center_lonlat.lon * 1000000)/1000000;
obj.spn=/* variable declaration */;
return obj;
}

$(document).ready(function() {
// this replaces the original doc-ready call, but doesn't look like it's needed
calc_values();
});

$(document).ready(function() {
var obj = calc_values();
// you can now use obj.projI etc to generate your link
$('div .olControlAttribution').append('<a id="WMEtoGMM" href=" \
/* link here that uses above variables */"'+ \
'target="_blank">Open new page</a>');
});

$('div .view-area.olMap #mouseupElement').mouseup(function() {
var obj = calc_values();
// you can now use obj.projI etc to generate your link
$('#WMEtoGMM').attr('href', 'URL HERE');
});

关于javascript - 用户脚本中的可重用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com