通过url字符串使用javascript更改页面内容

通过url字符串使用javascript更改页面内容,javascript,string,url,Javascript,String,Url,我是一个设计师,不是一个JS程序员,所以在这方面有任何帮助都是很好的 使用javascript或jquery如何通过url中的字符串替换页面上的内容 因此,如果内容“A”只是通过此http://www.example.com 如果“A”通过此项被内容“B”替换http://www.example.com/index.html?content=b. 例如: 内容A <div id="video-player"> vimeo code </div> 是吗?最简单的方法是使用

我是一个设计师,不是一个JS程序员,所以在这方面有任何帮助都是很好的

使用javascript或jquery如何通过url中的字符串替换页面上的内容

因此,如果内容“A”只是通过此http://www.example.com 如果“A”通过此项被内容“B”替换http://www.example.com/index.html?content=b.

例如:

内容A

<div id="video-player">
vimeo code
</div>

是吗?

最简单的方法是使用哈希标记。你能用一把吗?但实施起来更难。因此,使用index.html?content=b代替index.html?content=b,然后您可以通过使用window.location.hash.substring1引用它,在您的场景中,它将为您提供b。然后可以使用if语句检查该值并相应地调整内容

或者,如果您需要使用?然后,您可以使用此窗口。location.href.split'?'[1]。split'content='[1],但它不能保证在所有情况下都能工作,特别是当您有多个变量时。对于多个变量,您将使用

window.location.href.split('?')[1].split('&')[0].split('content=')[1]
您的完整代码现在如下所示:

$(function () {
  var youtube_code, vimeo_code, content_value;
  youtube_code = "The code for Youtube goes here";
  vimeo_code = "The code for Vimeo goes here";
  content_value = (typeof window.location.href.split('player=')[1] !== "undefined") ? window.location.href.split('player=')[1] : "";

  if (content_value === "youtube") {
    $('#video-player').html(youtube_code);
  } else {
    $('#video-player').html(vimeo_code);
  }
});
如果您想要更多内容选项,还可以使用其他一些ifs。根据您选择的选项,使用前两行中的一行

编辑:将代码更改为完整代码并进行了一些优化。除了将youtube_代码和vimeo_代码更改为正确的值之外,您不需要添加任何其他内容


编辑:优化并使其检查url中是否确实有player=。

我建议您使用ajax和xml。将xml文件放在dropbox文件夹中,您可以随时编辑url

如果用户选择一个选项,ajax将在不刷新浏览器的情况下更新该值


好消息是,您可以在不登录html编辑器/网站cms的情况下从手机更新url,并且您还可以使用其他功能

更准确一点。是否要加载页面中的某个位置?或者阅读URL,查看是否找到content=b,然后在某处显示某个内容?因此,如果URL中没有字符串,我只希望它显示内容“A”,但如果URL中有类似content=b的字符串,则我希望将“A”的内容替换为“b”。这将是一个女主角哈,是的。我想可能是这个。让我找出一种方法来解决这个问题并更改代码……jQuery 1.3.2非常古老。包括以下内容:试着转到你的链接,看看会发生什么。这就是为什么它不起作用的原因:P这是有效的,我把它改成了你建议的那个,但它仍然是一样的。。。没有什么比你在上面的链接中给我看的更像的了。。。。我很抱歉今晚让你头痛,但你一直都很好
window.location.href.split('?')[1].split('&')[0].split('content=')[1]
var content_value = window.location.hash.substring(1) // For hashses OR
var content_value = window.location.href.split('?')[1].split('&')[0].split('content=')[1] // For ?
if (content_value === "b") {
  $('#video-player').html(vimeo_code);
} else {
  $('#video-player').html(youtube_code);
window.location.href.split('?')[1].split('&')[0].split('content=')[1]
$(function () {
  var youtube_code, vimeo_code, content_value;
  youtube_code = "The code for Youtube goes here";
  vimeo_code = "The code for Vimeo goes here";
  content_value = (typeof window.location.href.split('player=')[1] !== "undefined") ? window.location.href.split('player=')[1] : "";

  if (content_value === "youtube") {
    $('#video-player').html(youtube_code);
  } else {
    $('#video-player').html(vimeo_code);
  }
});