繁体   English   中英

如何拆分函数变量并在以后使用?

[英]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.

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