单击按钮时如何运行脚本 [英] How to run script when a button is clicked

查看:169
本文介绍了单击按钮时如何运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在为我制作的表单运行一些字段输入值的总和和乘法脚本。我怎样才能让这个脚本在点击按钮上运行,以便在用户输入新值后,他们可以点击更新表单按钮来运行计算脚本并更新总金额。

 < script> 
$ b var $ form = $('#contactForm'),
$ summands = $ form.find('。sum1'),
$ sumDisplay = $('#itmttl );
$ b $ form.delegate('。sum1','change',function()
{
var sum = 0;
$ summands.each(function( )
{
var value = Number($(this).val());
if(!isNaN(value))sum + = value;
});

$ sumDisplay.val(sum);
});




函数乘(一,二){
if(one&& two){
this.form。 elements.tax.value = 1 * 2;
} else {
this.style.color ='blue';
}
}

< / script>


解决方案

定义一个函数并将您想运行的代码在里面。

  var doStuff = function(){
//在这里做一些事
};

选择您的按钮并在点击时调用该功能。如果您使用的是 A BUTTON 标签,您可能想要阻止默认操作在这个例子中。
$ b $ pre $ $('。button')。on('click',function(event){
doStuff();
event.preventDefault();
});

这假设您使用的是jQuery 1.7 +。

Hi I'm running a sum and multiplication script for some field input values to a form i made. How can I get this script to run on a button click so that after a user enters a new value they can click a update form button to run the calculations script and update the total sum.

<script>

var $form = $('#contactForm'),
    $summands = $form.find('.sum1'),
    $sumDisplay = $('#itmttl');

$form.delegate('.sum1', 'change', function ()
{
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $sumDisplay.val(sum);
});




function multiply(one, two) {
  if(one && two){
    this.form.elements.tax.value = one * two;
  } else {
    this.style.color='blue';
  }
}

</script>

解决方案

Define a function and put the code you want to run inside it.

var doStuff = function () {
  // do some stuff here
};

Select your button and call that function on click. If you're using an A or BUTTON tag you may want to prevent the default action, which I've included in this example.

$('.button').on('click', function (event) {
  doStuff();
  event.preventDefault();
});

This assumes that you're using jQuery 1.7+.

这篇关于单击按钮时如何运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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