首页 > 解决方案 > (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 有这种行为,因此我的计划被毁了:)。

谢谢您的帮助。

标签: javascriptjqueryeventspage-refreshonload-event

解决方案


我最终找到了一个开箱即用的解决方案:)。

/************ 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();
 };

它奏效了,这就是它所需要的:)


推荐阅读