gpt4 book ai didi

javascript - 如何将 URL 动态添加到 javascript 中,以使第二页的 div 显示在第一页上?

转载 作者:行者123 更新时间:2023-11-30 17:17:48 25 4
gpt4 key购买 nike

好的,这就是我所拥有的,对于起始代码:

$(document).ready(function(){
$('.currentpagediv').load('http://theurl.com/page2/somethingsomewhere.html .secondpagedivclass');
});

它的作用是在当前页面上找到 div,<div class="currentpagediv"> , 并在第二页 ( http://theurl.com/page2/somethingsomewhere.html ) div <div class="secondpagedivclass"> 中添加

例如,假设我有一个这样的页面:

<html>
<body>
<div class="currentpagediv">
</div>
</body>
</html>

然后我上面的代码所做的就是:

<html>
<body>
<div class="currentpagediv">
</div>
<div class="secondpagedivclass">
</div>
</body>
</html>

这正是我想要它做的。这样我就有了我需要的功能。

但是,问题是我需要 URL 部分是动态
例如,当前页面始终为 http://theurl.com/page1/[a path].html ,我需要获取 div 的新页面始终是 http://theurl.com/page2/[the same path].html

所以基本上,我需要获取 URL,并且只更改 /page1//page2/ ,同时保留这一点。这样我就可以在域的所有页面上运行,它会添加来自 page2 的部分进入page1 .

像这样:


原始页面http://theurl.com/page1/365743668.html :

<html>
<body>
<div class="currentpagediv">
</div>
</body>
</html>

第二页http://theurl.com/page2/365743668.html :

<html>
<body>
<div class="secondpagedivclass">
</div>
</body>
</html>

脚本正在运行的新原始页面(仍为 http://theurl.com/page1/365743668.html ):

<html>
<body>
<div class="currentpagediv">
</div>
<div class="secondpagedivclass">
[THE INFO FROM PAGE `http://theurl.com/page2/365743668.html`]
</div>
</body>
</html>

我试过很多东西,但都没有用。

这是我的尝试,但没有成功:


function changeURL() {
var theURL = location.pathname.toString();
var newURL = theURL.replace("/page1/", "/page2/");
}
$(document).ready(function(){
$('.currentpagediv').load(changeURL() '.secondpagedivclass');
});

在上面的代码中,我试图:

  1. 获取当前页面的url
  2. 将 url 转换为字符串,这样我就可以
  3. 修改url,然后
  4. 添加函数changeURL()代替 URL 在 .load(' 之后的位置

请注意,我想使用 jquery这个方法(不是另一种方法)让它工作,因为我也在努力学习,并给我一些完全不同的东西不会帮助我学习如何执行此方法。

最佳答案

您只是缺少字符串连接操作,+

$('.currentpagediv').load(changeURL() + ' .secondpagedivclass');

不要忘记 .secondpagedivclass 之前的空格。

changeURL函数需要返回结果:

function changeURL() {
var theURL = location.pathname;
var newURL = theURL.replace("/page1/", "/page2/");
return newURL;
}

您不需要使用 .toString(),因为路径名是一个字符串。

关于javascript - 如何将 URL 动态添加到 javascript 中,以使第二页的 div 显示在第一页上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com