代码清理 - 几个jQuery弹出窗口



我正在使用一个重复模块供客户端在页面上的每个产品上弹出弹出窗口。我有效的代码,但我认为它非常肿,可能有一种更简洁的方法。找到更清洁的写作方法的任何帮助确实会有所帮助。

$(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" });
    });
});

这应该为您带来技巧:

$(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>

最新更新