gpt4 book ai didi

javascript - addEventListener 仅在页面刷新时起作用?

转载 作者:行者123 更新时间:2023-11-30 05:52:39 26 4
gpt4 key购买 nike

我正在修改两个下拉列表的外观。这里没有问题。一切都很好。唯一的问题是 addEventListener 方法仅在页面刷新时有效。

如何在不点击刷新按钮的情况下让这段代码在页面加载时工作?

window.addEventListener('load', function () 
{
var CityCount = this.character.citynum ;
var PosX = parseInt(CityCount) * (-15);
var MyHeight = parseInt(CityCount) * 15 - 15;
var MyStyle='div#citylist {width: 150px !important; margin-top: ' + PosX + 'px !important; position: absolute !important; height: ' + MyHeight + 'px !important; overflow: auto !important; padding-left: 1px !important}';
addGlobalStyle(MyStyle);
addGlobalStyle('div#my_city_list {width: 150px !important; margin-top: 50px !important;}');
}, false)

最佳答案

您没有列出目标页面,但它可能使用 AJAX 来设置和/或更改该全局变量。

此外,如果脚本丢失了它的 @grant none,问题代码将会中断。状态,或者如果您尝试在 Firefox 以外的任何浏览器上使用它。 (除非脚本使用注入(inject)——我们无法从问题中分辨出来。)

要解决 AJAX 问题,请轮询 setInterval() 中的变量。
要使代码更健壮,请使用 unsafeWindowScript Injection。参见 "Accessing Variables from Greasemonkey..."获取更多信息。

将所有这些放在一起,这应该可行。不需要 addEventListener():

var globScope       = unsafeWindow || window;
var cityCountTimer = setInterval (styleTheCityList, 333);

function styleTheCityList () {
this.lastCityCount = this.lastCityCount || 0; // Static var for this func

if (
typeof globScope.character != "undefined"
&& typeof globScope.character.citynum != "undefined"
) {
var CityCount = parseInt (globScope.character.citynum, 10);
if (CityCount != this.lastCityCount) {
var PosX = CityCount * (-15);
var MyHeight = CityCount * 15 - 15;
var MyStyle = 'div#citylist {width: 150px !important; margin-top: '
+ PosX
+ 'px !important; position: absolute !important; height: '
+ MyHeight
+ 'px !important; overflow: auto !important; padding-left: 1px !important}'
;
addGlobalStyle (MyStyle);
addGlobalStyle ('div#my_city_list {width: 150px !important; margin-top: 50px !important;}');

this.lastCityCount = CityCount;
}
}
}

关于javascript - addEventListener 仅在页面刷新时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13771066/

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