我知道通过js或jQuery在容器框架中加载页面或文件的基本知识,但通过像onClick 这样的事件监听器
JS-
document.getElementById("id").innerHTML = "<object type = 'text/html' data = 'myfile.html'> </data>"
JQUERY-
$("#id").load("myfile.txt");
但我想要实现的是与此相同,但不仅仅是在容器框架中加载onClick
,而且还在url上添加一个参数,例如:
if I click on a button, `webpage.html` will load on `<div>` container frame, and the `url` will change to `http://example.com/?loaded=webpage.html`
我想这样做,所以我可以更改url
字符串,也可以按element
并在div
容器框架上加载某个文件。
与facebook管理profile.php
的原理相同
http://facebook.com/profile.php?=mypersonalprofile
-加载我的配置文件http://facebook.com/profile.php?=myfriendsprofile
-加载我的朋友档案
我希望我能把它说清楚。
我认为这将展示您在寻找
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<button class="loadButton" value="input1.txt">Load file 1</button>
<button class="loadButton" value="input2.txt">Load file 2</button>
<div id="view"></div>
</body>
<script>
$(function(){
// Call loadPage on init
loadPage();
$(".loadButton").on("click", function(){
// Change URL, you can change "/testJS/index.html" to suit your web address
history.pushState({}, "", "/testJS/index.html?loaded=" + $(this).attr("value"));
$("#view").empty();
$("#view").load($(this).attr("value"));
});
});
function loadPage() {
console.log("start");
var href = window.location.href;
var index = href.indexOf("?loaded=");
// Load data if we define the loaded param
if (index > -1) {
data = href.substring(index + 8);
console.log(index + " " + data);
$("#view").empty();
$("#view").load(data);
}
}
</script>
</html>
您需要结合Get-url参数jquery或How to GetQuery String Values In js的解决方案,在不重新加载页面的情况下修改url。
您可以使用设置页面
history.pushState({}, "", "/mainpage.html?loaded=webpage.html");
$("#id").load("webpage.html");
然后,如果他们以其他方式更改url(这将需要重新加载页面(,您可以从url中获取参数并加载它:
var myfile = getUrlParameter("loaded");
$("#id").load(myfile);
getUrlParameter函数定义为:
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};