【问题标题】:Making Javascript Code Deploy Ready准备好 Javascript 代码部署
【发布时间】:2017-06-27 05:40:31
【问题描述】:

我需要准备好此代码部署。我无法对这些 URL 进行硬编码,但由于某种原因,任何其他编码方式都会中断。在此处引用此问题:Upon Redirect of Form Submission within iFrame jQuery Not Detecting Updated Src Attribute

我基本上需要让开关检查位置是否在“settings/”之后包含页面名称,即 iframe-home.php、update.php 或 changepassword.php。我想这就是我解决这个问题的方法?但我不确定如何。 (希望这是有道理的)

代码如下:

$(document).ready(function() {
    $('iframe#settings-iframe').on('load', function() {
    var location = this.contentWindow.location.href;
    console.log('location : ', location);
    switch (location) {
        case "http://localhost/Makoto/profile/settings/iframe-home.php":
        console.log(location);
        activateHome();
        break;
      case "http://localhost/Makoto/profile/settings/changepassword.php":
        console.log(location);
        activatePassword();
        break;
      case "http://localhost/Makoto/profile/settings/update.php":
        console.log(location);
        activateName();
        break;
    }
  });
});

【问题讨论】:

  • 向每个页面添加不同的代码而不是将其添加到所有页面并执行其中的一部分不是更容易吗?这样,如果您在 update.php-page 上,您只需执行代码,而不必担心需要执行哪些代码。
  • @Esko 如果iframe 有动态 URL 怎么办?

标签: javascript jquery


【解决方案1】:

注意我假设您想要动态检查没有主机部分的路径。

创建新的链接元素,将href设置为location,将其与pathname进行比较

// replace with this.contentWindow.location.href
var url = "http://localhost/Makoto/profile/settings/iframe-home.php";

/**
 * http://localhost/Makoto/profile/settings/iframe-home.php
 * will return /Makoto/profile/settings/iframe-home.php
 */
var link = $('<a>', {
  href: url
})[0].pathname;

var parts = link.split('/');
var file = parts[parts.length - 1];

console.log(file);

switch (file) {
  case "iframe-home.php":
    activateHome();
    break;
  case "changepassword.php":
    activatePassword();
    break;
  case "update.php":
    activateName();
    break;
}

function activateHome() {console.log('Activating home');}
function activatePassword() {console.log('Activating password');}
function activateName() {console.log('Activating name');}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 2010-10-16
    • 2019-05-05
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多