【问题标题】:Code Clean up - Several JQuery Popups代码清理 - 几个 JQuery 弹出窗口
【发布时间】:2018-02-25 17:51:01
【问题描述】:

我正在为客户使用重复模块,以便在其页面上的每个产品元素上弹出一个弹出窗口。我的代码可以工作,但我想它非常臃肿,可能有一种方法可以更简洁地编写它。任何帮助找到一种更简洁的方式来编写它都会很有帮助。

$(document).ready(function() {
    $("a.popbtn1").on("click", function(e) {
        e.preventDefault();
        $(this).simplePopup({ type: "html", htmlSelector: "#poppost1" });
    });
    $("a.popbtn2").on("click", function(e) {
        e.preventDefault();
        $(this).simplePopup({ type: "html", htmlSelector: "#poppost2" });
    });
    $("a.popbtn3").on("click", function(e) {
        e.preventDefault();
        $(this).simplePopup({ type: "html", htmlSelector: "#poppost3" });
    });
    $("a.popbtn4").on("click", function(e) {
        e.preventDefault();
        $(this).simplePopup({ type: "html", htmlSelector: "#poppost4" });
    });
});

【问题讨论】:

    标签: jquery dry code-cleanup


    【解决方案1】:

    这应该对你有用:

    $(document).ready(function() {
      $("a[class^=popbtn]").on("click", function(e) {
        e.preventDefault();
        var theClass = $(this).attr("class").match(/popbtn[\w-]*\b/).toString().replace("popbtn", "");
        console.log(theClass)
        $(this).simplePopup({
          type: "html",
          htmlSelector: "#poppost" + theClass
        });
      });
    
    });
    

    演示

    $(document).ready(function() {
      $("a[class^=popbtn]").on("click", function(e) {
        e.preventDefault();
        var theClass = $(this).attr("class").match(/popbtn[\w-]*\b/).toString().replace("popbtn", "");
        console.log(theClass)
        $(this).simplePopup({
          type: "html",
          htmlSelector: "#poppost" + theClass
        });
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" class="popbtn1">test</a>

    【讨论】:

    • 嗯,由于某种原因,它似乎不起作用。我什至没有收到“theClass”的控制台日志弹出窗口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多