javascript - (window).load 函数在刷新时不起作用
问题描述
我有一个页面,我在 window.onload 中有一个函数来模拟对元素的点击。只有在页面完全加载时才会发生这种点击。事实证明,该功能在您第一次进入该页面时起作用。之后它停止工作。即使屏幕上没有某些元素,也要关闭该功能。
这是我的简单功能:
function clickOnMarker(){
alert('click on marker');
var markerName = jQuery(".entry-title").text();
jQuery( 'div[title="' + markerName + '"]' ).trigger( 'click' );
alert('Fez clique no marker');
}
window.onload = function() {
clickOnMarker();
};
该函数读取标题的值并单击标记(HeroMap 插件 - WordPress)以聚焦。事实证明,在运行一次序列后,即使地图上没有标记,该函数也会运行。
有没有办法控制这种行为并始终确保脚本仅在标记位于页面上时运行?据我所见,window.onload 有这种行为,因此我的计划被毁了:)。
谢谢您的帮助。
解决方案
我最终找到了一个开箱即用的解决方案:)。
/************ GLOBAL VARIABELS **************/
var numAttempts = 15; // Number of attempts for the function's CallBack. Avoid Loop
/*********** CLICK ON MARKER ************/
function clickOnMarker(){
var markerName = jQuery(".entry-title").text(); // Get text value (Title) on the Spots page
if(numAttempts > 0){ // If that checks if there are no more attempts to CallBack the function clickOnMarker()
if(jQuery( 'div[title="' + markerName + '"]' ).length > 0){ // If to Checks whether the element already exists in the page's DOM
var markerName = jQuery(".entry-title").text();
jQuery( 'div[title="' + markerName + '"]' ).trigger( 'click' );
numAttempts = 10; // If the click was successful madein the marker the global variable must be reseted
return;
}else{
callBackClickOnMarker(); // If the element does not exist in the DOM, it is called the CallBacK control function
}
}else{
numAttempts = 10; // If the number of attempts is exhausted the variable must be assigned the default value
return;
};
};
/********** CALLBACK *************/
function callBackClickOnMarker(){
// Function to call the function again with a delay of x mileseconds
setTimeout(function(){
clickOnMarker();
}, 1500); // Set the value in mileseconds of delay here for the action to be executed
numAttempts -= 1; // 1 is subtracted to variable that controls the number of attempts
};
/*************** ON LOAD FUNCTION *************/
window.onload = function() {
clickOnMarker();
};
它奏效了,这就是它所需要的:)
推荐阅读
- css - 找不到适合此布局的 flexbox
- asp.net-core - asp.net core 2.2 发布请求未到达端点
- apache - XAMPP 错误:启动 Apache 服务时遇到错误(Apache 意外关闭)
- json - Swift:有办法快速调试可解码对象
- c++ - 如何修复无效的 API 密钥、IP 或操作权限错误?
- java - 为什么我的实例变量没有被@Inject 初始化为null?
- php - 将数字添加到foreach循环php
- azure - 带有 Azure DevOps 版本的环境变量以及 Azure 应用服务和 Docker
- python-3.7 - 在使用底图时确定是否存在海岸线
- ios - 当 flatMapped 时,Combine 的 Future 永远不会完成