在文档加载时以及单击某个元素时运行 JS 函数
P粉777458787
P粉777458787 2023-09-15 14:26:54
0
1
389

我正在尝试编写 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 );
 })();
热门教程
더>
最新下载
더>
网站特效
网站源码
网站素材
프론트엔드 템플릿
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!