简体   繁体   English

jquery .each()函数仅在浏览器“返回”按钮上生效

[英]jquery .each() function taking effect on browser “go back” button only

I currently have a webpage where I'm loading a div from another page using .load(). 我目前有一个网页,正在使用.load()从另一个网页加载div。 After I do the loading I run some jquery code to append a specific url to all the existing hrefs. 完成加载后,我运行一些jquery代码以将特定的URL附加到所有现有的href中。 The issue is that the first time I click on a hyperlink/href I am redirected to the old href. 问题是我第一次单击超链接/ href时,我被重定向到旧的href。 But after I click the "go back" button on my browser, and I try the same hyperlink/href, the href works and takes me to the new appended href. 但是,当我单击浏览器上的“返回”按钮,并尝试使用相同的超链接/ href后,href起作用并带我到新附加的href。

I would like to see if there is anyway to have all my hrefs change when I first load the page. 我想看看是否在我第一次加载页面时更改了我的所有hrefs。

Here is my code: 这是我的代码:

1st I initialize the container where I will be loading the container from the second page. 首先,我初始化容器,将在第二页中加载容器。

<pre>
  <code id="iframe-fragment"></code>
</pre>

2nd I load the second page's container into my current webpage. 第二,我将第二页的容器加载到当前网页中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<link href="https://roboticsys.com/support/plugins/servlet/docs/c1001-d1003/RapidCode/rsi_stylesheet.css" rel="stylesheet" type="text/css">
<script>
  $('#iframe-fragment').load('https://roboticsys.com/support/plugins/servlet/docs/c1001-d1003/RapidCode/_absolute_motion_8cs-example.html div.fragment'); 
</script>

3rd I append a url to all the hrefs in the imported container. 第三,我在导入的容器中的所有href后面附加一个URL。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("a").each(function() {
      var $this = $(this);       
      var _href = $this.attr("href"); 
      $this.attr("href", 'https://appended-url.com/' + _href);
    });
  });
</script>

Thank you in advance. 先感谢您。

Seems your load() content is being browser cached and apparent as content on the page once you hit the back button. 似乎您的load()内容正在浏览器中缓存,并在您单击后退按钮后显示为页面上的内容。

However before this, on initial page load, your document is complete, and runs your each, but the load isn't complete. 但是,在此之前,在初始页面加载时,您的文档已经完成,并且可以运行每个文档,但是加载并不完整。 In that scenario your content wouldn't be updated. 在这种情况下,您的内容将不会更新。

I'd rather update the URLs via the load complete callback: 我宁愿通过load complete回调来更新URL:

$('#div').load('http://myurl', function(res, status, xhr){
    //You can use the parameters for any sort of conditionals
    $('a').each(function(){
      //your code to edit the URLs
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM