运行JavaScript函数在文档加载时以及当特定元素被点击时[Tampermonkey]

huangapple go评论92阅读模式
英文:

Run JS function on document load and when a certain element is clicked [Tampermonkey]

问题

I'm here to assist with your translation request. Here's the translated part of your code:

  1. 我正在尝试编写一个Tampermonkey脚本来扩展我使用的业务Web应用程序在非常基本的意义上页面上会出现某些URL我需要从URL中提取一个数字然后使用该数字构建一个新链接并追加到父元素上
  2. 到目前为止我有以下代码但当我单击元素分页仅为UL或文档加载时它不起作用我知道该函数可以工作因为当我将其设置为在文档的任何位置单击时运行时它可以工作就好像页面在JS报告加载完全之前并没有完全加载一样

(function() {
'use strict';

  1. // 获取分页元素
  2. var element = document.getElementsByClassName('pagination-sm');
  3. element.onclick = createLinks;
  4. document.onload = createLinks;
  5. function createLinks() {
  6. var links = document.querySelectorAll("a[href*='/Field/POPendingCreate/']");
  7. for (var J = links.length-1; J >= 0; --J) {
  8. var thisLink = links[J];
  9. console.log(thisLink.href);
  10. var ppon = thisLink.href.match(/\d+/)[0];
  11. console.log(ppon);
  12. var a = document.createElement('a');
  13. var linkText = document.createTextNode("Preview Order");
  14. a.appendChild(linkText);
  15. a.title = "Preview Order";
  16. a.href = "https://website.com/Field/DownloadPendingPO?POPPKeyID=" + ppon + "&co=1&po=" + ppon;
  17. a.target = "_blank";
  18. var parentNode = thisLink.parentNode;
  19. console.log(parentNode);
  20. parentNode.appendChild(a);
  21. }
  22. }

})();

  1. UL元素看起来像这样:

```

如我上面所说,当我将其设置为在文档的任何位置单击时运行时,该函数按预期工作。对我更令人困惑的是,当使用document.onload时它不起作用。就好像页面只有在我开始与其交互后才开始加载数据。我尝试让函数在单击分页时运行的原因是因为页面似乎会获取所有数据并将其存储在某个地方(我无法看到),然后只是在分页时切换页面。因此,一旦单击分页,我确实需要在新页面上生成的链接上运行该函数。

似乎我需要延迟运行document.onload或其他一种方式来知道文档数据何时加载完全,以及为什么它不会在单击UL分页元素时运行?

  1. I've provided the translation for your code as requested. If you need any further assistance, please let me know.
  2. <details>
  3. <summary>英文:</summary>
  4. I&#39;m trying to write a Tampermonkey script to extend a business web app I use. In a very basic sense, certain URL&#39;s appear on the page, I need to extract a number from the URL then use than number to build a new link and append to the parent element.
  5. So far I have this but it&#39;s not working when I click on the element (pagination just an UL) or on document load. I know the function works as when I set it to run on clicking anywhere in the document it works. It&#39;s almost like the page isn&#39;t fully loaded when JS reports it is loaded.

(function() {
'use strict';

  1. //get the pagination element
  2. var element = document.getElementsByClassName(&#39;pagination-sm&#39;);
  3. element.onclick = createLinks;
  4. document.onload = createLinks;
  5. function createLinks() {
  6. var links = document.querySelectorAll (&quot;a[href*=&#39;/Field/POPendingCreate/&#39;]&quot;);
  7. for (var J = links.length-1; J &gt;= 0; --J) {
  8. var thisLink = links[J];
  9. console.log(thisLink.href);
  10. var ppon = thisLink.href.match(/\d+/)[0];
  11. console.log(ppon);
  12. var a = document.createElement(&#39;a&#39;);
  13. var linkText = document.createTextNode(&quot;Preview Order&quot;);
  14. a.appendChild(linkText);
  15. a.title = &quot;Preview Order&quot;;
  16. a.href = &quot;https://website.com/Field/DownloadPendingPO?POPPKeyID=&quot; + ppon + &quot;&amp;co=1&amp;po=&quot; + ppon;
  17. a.target = &quot;_blank&quot;;
  18. var parentNode = thisLink.parentNode;
  19. console.log(parentNode);
  20. parentNode.appendChild(a);
  21. }
  22. }

})();

  1. The UL element just looks like this:

<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>

  1. As I said above the function works as expected when I set it to run on clicking anywhere on the document. More puzzling to me is that it doesn&#39;t work when using document.onload. It&#39;s like the page only starts loading data in once I start interacting with it. The reason why I&#39;m trying to have the function run when clicking on the pagination is because the page appears to get all the data and store it somewhere (I can&#39;t see) then just flicks through the pages when paginating. So once the pagination is clicked I really need to run the function on the links that are generated on the new page.
  2. Seems like I need to delay running document.onload or some other way of knowing once the document data has loaded and also work out why it won&#39;t run when clicking on the UL pagination element?
  3. </details>
  4. # 答案1
  5. **得分**: 2
  6. 以下是您要翻译的内容:
  7. "Instead of waiting for the page to render and then looping through all the elements to attach an anchor tag. Just use a MutationObserver to handle any elements that get rendered after you have run your logic.
  8. **JS**
  9. ```js
  10. (function() {
  11. 'use strict';
  12. const createLinks = function ( nodeElement ){
  13. const queryElem = nodeElement.parentElement || nodeElement;
  14. const links = queryElem.querySelectorAll("a[href*='/Field/POPendingCreate/']");
  15. for ( const link of links || [] ){
  16. // Skip link if Preview has been attached
  17. if ( link.createLinkReady ) continue;
  18. // Get numbers from link href
  19. const [ ppon ] = link.href.match(/\d+/);
  20. // Create an anchor tag
  21. const a = document.createElement('a');
  22. a.innerHTML = 'Preview Order';
  23. a.setAttribute( 'title', 'Preview Order' );
  24. a.setAttribute( 'href', `https://website.com/Field/DownloadPendingPO?POPPKeyID=${ppon}&co=1&po=${ppon}` );
  25. a.setAttribute( 'target', '_blank' );
  26. a.setAttribute( 'rel', 'nofollow' );
  27. // Append anchor tag to parent element
  28. link.parentElement.appendChild( a );
  29. link.createLinkReady = true;
  30. }
  31. }
  32. // Create DOM MutationObserver
  33. const Observer = new MutationObserver( function( mutationsList ) {
  34. // Loop through mutations
  35. for ( const mutation of mutationsList || [] ) {
  36. // Loop through added nodes
  37. for ( const node of mutation.addedNodes || [] ){
  38. // Run createLinks on node
  39. createLinks( node );
  40. }
  41. }
  42. });
  43. // Observe DOM for new elements starting from document.body
  44. Observer.observe( document.body, { childList:true, subtree:true } );
  45. // Process links that have been rendered
  46. createLinks( document.body );
  47. })();

请注意,我已将代码中的HTML实体编码(如&quot;&#39;)还原为正常的引号和双引号。

英文:

Instead of waiting for the page to render and then looping through all the elements to attach an anchor tag. Just use a MutationObserver to handle any elements that get rendered after you have run your logic.

JS

  1. (function() {
  2. &#39;use strict&#39;;
  3. const createLinks = function ( nodeElement ){
  4. const queryElem = nodeElement.parentElement || nodeElement;
  5. const links = queryElem.querySelectorAll(&quot;a[href*=&#39;/Field/POPendingCreate/&#39;]&quot;);
  6. for ( const link of links || [] ){
  7. // Skip link if Preview has been attached
  8. if ( link.createLinkReady ) continue;
  9. // Get numbers from link href
  10. const [ ppon ] = link.href.match(/\d+/);
  11. // Create an anchor tag
  12. const a = document.createElement(&#39;a&#39;);
  13. a.innerHTML = &#39;Preview Order&#39;;
  14. a.setAttribute( &#39;title&#39;, &#39;Preview Order&#39; );
  15. a.setAttribute( &#39;href&#39;, `https://website.com/Field/DownloadPendingPO?POPPKeyID=${ppon}&amp;co=1&amp;po=${ppon}` );
  16. a.setAttribute( &#39;target&#39;, &#39;_blank&#39; );
  17. a.setAttribute( &#39;rel&#39;, &#39;nofollow&#39; );
  18. // Append anchor tag to parent element
  19. link.parentElement.appendChild( a );
  20. link.createLinkReady = true;
  21. }
  22. }
  23. // Create DOM MutationObserver
  24. const Observer = new MutationObserver( function( mutationsList ) {
  25. // Loop through mutations
  26. for ( const mutation of mutationsList || [] ) {
  27. // Loop through added nodes
  28. for ( const node of mutation.addedNodes || [] ){
  29. // Run createLinks on node
  30. createLinks( node );
  31. }
  32. }
  33. });
  34. // Observe DOM for new elements starting from document.body
  35. Observer.observe( document.body, { childList:true, subtree:true } );
  36. // Process links that have been rendered
  37. createLinks( document.body );
  38. })();

huangapple
  • 本文由 发表于 2023年7月18日 08:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定