【问题标题】:writing reusable code to create a like button that increments编写可重用的代码来创建一个递增的类似按钮
【发布时间】:2013-10-30 15:02:35
【问题描述】:

为了这周的一些练习,我尝试创建一个博客页面的前端。我添加了一些“假”的 Like 按钮(它们不附加到 facebook,只需举起放在它们旁边的计数器。)

一切正常,尽管我认为有一种更直接和可重用的方式来编写我用来构建这些计数器的 jQuery/JavaScript 代码。

这是 JavaScript 代码:

<script>
var whichButton = "";
var counter = 0;                        // Adds counters next to each 
var counter2 = 0;                       // "Like" button, and raises
$("button").on("click", function(){     // their values separately.
  whichButton = this.id;                   
  if (whichButton === "button1") {        
    counter++; 
    $("#span1").html(counter);
  } else {
    counter2++
    $("#span2").html(counter2);
  }
});
</script>

...这是它影响的 html:

<button id="button1">Like</button>
<span id="span1"></span>
<button id="button2">Like</button>
<span id="span2"></span> 

有没有更简单的方法来编写这段代码?可以让我 在新跨度旁边添加新按钮,两者都具有互补 ID,并且在不更新我的 JavaScript 代码的情况下,我的网站是否允许每个按钮自动运行?

我正在尝试以最有效的方式来写这篇文章。

谢谢!

【问题讨论】:

    标签: javascript jquery code-reuse


    【解决方案1】:

    要使其成为更可重用的组件,请利用类而不是唯一 ID。

    $(".like_button button").on("click", function() {
      var $count = $(this).parent().find('.count');
      $count.html($count.html() * 1 + 1);
    });
    

    在您的标记中,创建任意数量的 like_button 实例,并使用 HTML 设置默认值 0

    <div class="like_button">
      <button>Like</button>
      <span class="count">0</span>
    </div>
    

    注意: $(this).parent().find('.count'); 是一个非常字面的遍历示例。您可以使用$(this).next(); 来查找按钮的下一个兄弟,这样就不再需要“count”类。查看jQuery Docs on Traversal 了解许多其他精彩方法。

    这是一个显示实际效果的小提琴:http://jsfiddle.net/bw5LU/

    【讨论】:

    • 非常感谢!自从我开始学习 jQuery 之后,这变得更有意义了。
    【解决方案2】:

    当然,用类或其他属性标记所有喜欢的按钮,以便我们可以选择喜欢:

    $(".like-button").on("click", function(e){
        var $counter = $(this).find(".count");
        var count = $counter.text() | 0; //corose current count to an int
        $counter.text(count + 1);//set new count
    });
    

    现在要创建新的类似按钮,请在 html 文档的任意位置添加以下 sn-p:

    <div class="like-button">
        <button>Like</button>
        <span class="count"></span>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多