Jquery中的正负增量器,如何概括? [英] Plus/minus incrementator in Jquery, how to generalize?

查看:92
本文介绍了Jquery中的正负增量器,如何概括?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码

<a id="minus" href="#">-</a>
   <span id="VALUE">0</span>
<a id="plus" href="#">+</a>

JavaScript:

Javascript:

$(function(){

    var valueElement = $('#VALUE');
    function incrementValue(e){
        valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0));
        return false;
    }

    $('#plus').bind('click', {increment: 1}, incrementValue);

    $('#minus').bind('click', {increment: -1}, incrementValue);

});

具有名为"VALUE"的字段的正负增量器. 现在,我有一个使用此表单的表单,其中包含150个这样的字段......有一种方法可以概括将此代码以某种方式传递给用户正在递增/递减的字段名称的函数? 否则,我必须将此代码复制150次...

to have a plus/minus incrementator of the filed named "VALUE". Now, i have a form using this containing 150 field like this... there's a way to generalize this code passing in some way to the function the name of the field that the user is incrementing/decrementing? Otherwise, i have to replicate this code 150 times...

推荐答案

如果有帮助,请尝试以下方法:

try this one if this helps:

我做了一些更改,我使用了classes .plus, .minus而不是ids #plus, #minus

i have changed a little bit i used classes .plus, .minus instead of ids #plus, #minus

 $('.plus').click(function() {
    var sp = parseFloat($(this).prev('span').text());
    $(this).prev('span').text(sp + 1);
 });

 $('.minus').click(function() {
    var sp = parseFloat($(this).next('span').text());
    $(this).next('span').text(sp - 1);
 });

在提琴中检查一下: http://jsfiddle.net/L2UPw/

check this out in fiddle: http://jsfiddle.net/L2UPw/

这篇关于Jquery中的正负增量器,如何概括?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆