【问题标题】:How can I make one function to load various ifram?如何制作一个函数来加载各种 iframe?
【发布时间】:2014-02-23 11:14:39
【问题描述】:

嗨,我有不同的页面要加载到同一个 iframe,所以我有这些功能

$("#a1").click(function () { 
      $("#frame").attr("src", "page1.html");
});
$("#a2").click(function () { 
      $("#frame").attr("src", "page2.html");
});
$("#a3").click(function () { 
      $("#frame").attr("src", "page3.html");
});

我怎样才能使函数只加载一个函数"page"+numid+".html"

【问题讨论】:

    标签: jquery iframe load


    【解决方案1】:

    使用Multiple Selector ("selector1, selector2, selectorN")

    $("#a1, #a2, #a3").click(function () { 
         var num = this.id.match(/\d+/)[0]; //Extract number from ID
         $("#frame").attr("src", "page"+num +".html");
    });
    

    或者

    你可以使用Attribute Starts With Selector [name^="value"],虽然我不推荐

    $("[id^=a]").click(function () { 
         var num = this.id.match(/\d+/)[0]; //Extract number from ID
         $("#frame").attr("src", "page"+num +".html");
    });
    

    【讨论】:

    • @user3334919,很高兴我能帮上忙 :)
    【解决方案2】:

    Attribute Starts With Selector [name^="value"]

    $("[id^=a]").click(function () { 
          $("#frame").attr("src", "page"+this.id.replace('a')+".html");
    });
    


    或者

    .match(/\d+$/)[0]从id中获取号码

    $("[id^=a]").click(function () { 
          $("#frame").attr("src", "page"+this.id.match(/\d+$/)[0]+".html");
    });
    

    $("[id^=a]") --> 所有以 id 开头的元素 a

    【讨论】:

      【解决方案3】:

      您可以使用属性选择器 [attribute='value'] 选择带有 id 的元素,选择以 a 开头的 id 使用 [id^='a']
      使用slice()获取号码

      $("[id^=a]").click(function () { 
            $("#frame").attr("src", "page" + this.id.slice(1) + ".html/");
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多