[英]How to split a function variable and use it later on?
我正在為我正在制作的網站開發一個哈希系統,盡管我要哈希的某些頁面最后需要一個PHP id。 我不想在散列網址中包含.php,因此我嘗試將其拆分,以便稍后再插入。
html方面的示例。
<a href="#!/_radio/profile?id=3">link</a>
到目前為止,這就是我所擁有的。 除了結尾處不包含多余的變量外,所有其他方法均有效。
var Radio = {};
Radio = {
_jsInit: function () {
$(window).bind('hashchange', function () {
Radio._currentPage();
Radio.loadPage(Radio._PageName, Radio._extra)
});
$(window).trigger("hashchange")
},
_currentPage: function () {
this._PageName = location.hash.replace('#!/', '');
if (this._PageName == "") window.location = "#!/_radio/home";
this.values = this._PageName.split("?");
this._extra = this.values[1];
},
loadPage: function (page, extra) {
$('#content').fadeOut(200).load('_files/_v2/_pages/' + page + '.php?' + extra + '', function () {
$('#content').fadeIn(400)
});
},
};
$(document).ready(function () {
Radio._jsInit();
});
為此,之前和之后:
Before: "#!/_radio/profile?id=2"
After: "_files/_v2/_pages/profile.php?id=2"
您可以使用正則表達式查找所需的字符串部分:
function convertStr(str) { var matches = str.match(/(\\/[^\\/]+)(\\?.*$)/); return "_files/_v2/_pages" + matches[1] + ".php" + matches[2]; } // call the function and display the result in the snippet var result = convertStr("#!/_radio/profile?id=2"); document.write(result);
或者,任何使用.replace()
簡單版本:
function convertStr(str) { return str.replace(/(^.*)(\\/[^\\/]+)(\\?.*$)/, "_files/_v2/_pages$2.php$3"); } // call the function and display the result in the snippet var result = convertStr("#!/_radio/profile?id=2"); document.write(result);
在使用提供的代碼jfriend00之后,我開始工作了。
var Radio = {};
Radio = {
_jsInit: function () {
$(window).bind('hashchange', function () {
Radio._currentPage();
Radio.loadPage(Radio._PageName)
});
$(window).trigger("hashchange")
},
_currentPage: function () {
this._PageName = location.hash.replace('#!/', '');
if (this._PageName == "") window.location = "#!/_Radio/home";
},
loadPage: function (page) {
var matches = page.split("?");
var load = "_files/_v2/_pages/" + matches[0] + ".php?" + matches[1];
$("#content").fadeOut(200).load(load, function () {
$("#content").fadeIn(400)
});
},
};
$(document).ready(function () {
Radio._jsInit();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.