Script to fire an event as soon as an element exists?

随声附和 提交于 2020-01-11 07:49:08

问题


I'm trying to write a little Greasemonkey script for achieving some tasks in Facebook, like hiding news and such.

The problem is: I'm having an ID to an element which isn't existing yet in the DOM. It's the little box which appears when hitting a post's arrow-icon.

How can I create an event handler through jQuery which fires as soon as the element exists?


回答1:


This is a common problem. You can act on AJAXed-in elements as they appear by using the waitForKeyElements() utility. (See "Fire Greasemonkey script on AJAX request" for example.)

I'm not sure what you mean by "the little box which appears when hitting a post's arrow-icon", but in general, you would:

  1. Make sure your script has jQuery. Add this to the metadata section, if it's not there already:

    // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
    


  2. Require-in waitForKeyElements:

    // @require https://gist.github.com/raw/2625891/waitForKeyElements.js
    


  3. Write your handler function and activate it:

    function hideTheNews (jNode) {
        //***** YOUR CODE HERE *****
        jNode.hide (); // For example
    }
    
    waitForKeyElements ("*APPROPRIATE jQuery SELECTOR*", hideTheNews);
    


来源:https://stackoverflow.com/questions/10601570/script-to-fire-an-event-as-soon-as-an-element-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!