带有参数的内联javascript的jQuery替代方案

时间:2014-04-01 20:14:27

标签: javascript jquery

对于以下代码,jquery中的替代方法是什么?

function doSomething(par1, par2, par3) {
    // process something with the parameters
}

.
.
.
<div>
    <input type="button" value="Process" onclick="doSomething('a', 'b', 'c');"></input><br />
    <input type="button" value="Process" onclick="doSomething('d', 'e', 'f');"></input><br />
    <input type="button" value="Process" onclick="doSomething('g', 'h', 'i');"></input><br />
</div>

doSomething中使用的参数是在服务器端创建的。 谢谢!

编辑:补充问题

这将是最好的方式吗?

// On server side
$(function() {
    $('selector').click({par1:a, par2:b, par3:c}, function() {
       // process something with the parameters
    });
    $('selector').click({par1:d, par2:e, par3:f}, function() {
       // process something with the parameters
    });
    $('selector').click({par1:g, par2:g, par3:i}, function() {
       // process something with the parameters
    });
});

1 个答案:

答案 0 :(得分:0)

在单击上调用函数并将变量传递给它的替代方法? 您必须重新构建输入,以便除onlcick之外的某些边界(可能是&#39;值?&#39;)具有您想要传递的参数,然后这将是javascript。

<div>
     <input type="button" value="a,b,c"></input>
</div>


function doSomething(argumentsToManipulate) {
   ///expects an array of arguments
}


$('input').click(function(){
  ///passedArguments will be an ['a','b','c']
  var passedArguments = $(this).attr('value').split(',');
  doSomething(passedArguments);
});

另外,我很好奇为什么你不使用类或ID,因为这会使jquery选择更加具体。