在文件載入時以及點擊某個元素時執行 JS 函數
P粉777458787
P粉777458787 2023-09-15 14:26:54
0
1
628

我正在嘗試編寫 Tampermonkey 腳本來擴展我使用的商業 Web 應用程式。從非常基本的意義上來說,某些 URL 出現在頁面上,我需要從 URL 中提取一個數字,然後使用該數字建立新連結並附加到父元素。

到目前為止,我已經有了這個,但當我單擊元素(分頁只是 UL)或文檔加載時它不起作用。我知道該函數的工作原理與我將其設置為在單擊其工作的文檔中的任意位置時運行一樣。當 JS 報告頁面已加載時,這幾乎就像頁面尚未完全加載。

(function() {
    'use strict';

    //get the pagination element
    var element = document.getElementsByClassName('pagination-sm');
    element.onclick = createLinks;
    document.onload = createLinks;

    function createLinks() {
    var links = document.querySelectorAll ("a[href*='/Field/POPendingCreate/']");

        for (var J = links.length-1; J >= 0; --J) {
            var thisLink = links[J];
            console.log(thisLink.href);
            var ppon = thisLink.href.match(/\d+/)[0];
            console.log(ppon);

            var a = document.createElement('a');
            var linkText = document.createTextNode("Preview Order");
            a.appendChild(linkText);
            a.title = "Preview Order";
            a.href = "https://website.com/Field/DownloadPendingPO?POPPKeyID=" + ppon + "&co=1&po=" + ppon;
            a.target = "_blank";

            var parentNode = thisLink.parentNode;
            console.log(parentNode);
            parentNode.appendChild(a);

        }
    }

 })();

UL 元素如下圖所示:

<ul uib-pagination="" items-per-page="formData.itemPerPage" class="pagination-sm ng-pristine ng-untouched ng-valid ng-scope ng-isolate-scope pagination ng-not-empty" data-total-items="pendingList.length" data-ng-model="formData.currentPage" data-max-size="10" data-ng-if="!attachmentView &amp;&amp; filteredDocuments.length > 0" role="menu"><!-- ngIf: ::boundaryLinks -->
<!-- ngIf: ::directionLinks --><li role="menuitem" ng-if="::directionLinks" ng-class="{disabled: noPrevious()||ngDisabled}" class="pagination-prev ng-scope disabled"><a href="" ng-click="selectPage(page - 1, $event)" ng-disabled="noPrevious()||ngDisabled" uib-tabindex-toggle="" class="ng-binding" disabled="disabled" tabindex="-1">Previous</a></li><!-- end ngIf: ::directionLinks -->
<!-- ngRepeat: page in pages track by $index --><li role="menuitem" ng-repeat="page in pages track by $index" ng-class="{active: page.active,disabled: ngDisabled&amp;&amp;!page.active}" class="pagination-page ng-scope active"><a href="" ng-click="selectPage(page.number, $event)" ng-disabled="ngDisabled&amp;&amp;!page.active" uib-tabindex-toggle="" class="ng-binding">1</a></li><!-- end ngRepeat: page in pages track by $index -->
<!-- ngIf: ::directionLinks --><li role="menuitem" ng-if="::directionLinks" ng-class="{disabled: noNext()||ngDisabled}" class="pagination-next ng-scope disabled"><a href="" ng-click="selectPage(page + 1, $event)" ng-disabled="noNext()||ngDisabled" uib-tabindex-toggle="" class="ng-binding" disabled="disabled" tabindex="-1">Next</a></li><!-- end ngIf: ::directionLinks -->
<!-- ngIf: ::boundaryLinks -->
</ul>

正如我上面所說,當我將其設定為在單擊文件上的任意位置時運行時,該函數會按預期工作。更令我困惑的是,使用 document.onload 時它不起作用。就像頁面只有在我開始與其互動後才開始載入資料。我嘗試在單擊分頁時運行該函數的原因是因為該頁面似乎獲取了所有數據並將其存儲在某個地方(我看不到),然後在分頁時只是輕拂頁面。因此,一旦單擊分頁,我確實需要在新頁面上生成的連結上運行該函數。

似乎我需要延遲運行 document.onload 或其他一些了解文檔資料加載後的方式,並找出為什麼在單擊 UL 分頁元素時它不會運行?

P粉777458787
P粉777458787

全部回覆(1)
P粉122932466

而不是等待頁面呈現,然後循環遍歷所有元素以附加錨標記。只需使用 MutationObserver 來處理運行邏輯後呈現的任何元素。

JS

#
(function() {
    'use strict';

    const createLinks = function ( nodeElement ){
        const queryElem = nodeElement.parentElement || nodeElement;
        const links = queryElem.querySelectorAll("a[href*='/Field/POPendingCreate/']");

        for ( const link of links || [] ){
            // Skip link if Preview has been attached
            if ( link.createLinkReady ) continue;

            // Get numbers from link href
            const [ ppon ] = link.href.match(/\d+/);

            // Create an anchor tag
            const a = document.createElement('a');
            a.innerHTML = 'Preview Order';
            a.setAttribute( 'title', 'Preview Order' );
            a.setAttribute( 'href', `https://website.com/Field/DownloadPendingPO?POPPKeyID=${ppon}&co=1&po=${ppon}` );
            a.setAttribute( 'target', '_blank' );
            a.setAttribute( 'rel', 'nofollow' );

            // Append anchor tag to parent element
            link.parentElement.appendChild( a );
            link.createLinkReady = true;
        }

    }

    // Create DOM MutationObserver
    const Observer = new MutationObserver( function( mutationsList ) {
        // Loop through mutations
        for ( const mutation of mutationsList || [] ) {
            // Loop through added nodes
            for ( const node of mutation.addedNodes || [] ){
                // Run createLinks on node
                createLinks( node );
            }
        }
    });

    // Observe DOM for new elements starting from document.body
    Observer.observe( document.body, { childList:true, subtree:true } );

    // Process links that have been rendered
    createLinks( document.body );
 })();
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板