简体   繁体   English

如何将更改的输入值作为参数传递给另一个函数

[英]how to pass changed input value as param to another function

I have an input text field where the value could be incremented or decremented with plus and minus buttons. 我有一个输入文本字段,其中的值可以使用加号和减号按钮进行递增或递减。

I need to pass the value of this input field as a 3rd parameter to a function being called onclick in another button (all elements in the page loaded in the same time). 我需要将此输入字段的值作为第三个参数传递给另一个按钮中被称为onclick的函数 (页面中的所有元素同时加载)。

How do I do this with Javascript , not jQuery? 如何使用Javascript (而不是jQuery) 做到这一点 If I simply pass the name of the function, I get its body. 如果我简单地传递函数的名称,那么它将得到其主体。

JSFIDDLE JSFIDDLE

html: 的HTML:

<input type="button" onclick="updateQuantity('test','add')" value="+" />
<input type="button" onclick="updateQuantity('test','not')" value="-" />
<input type="button" onclick="getUpdatedQty()" value="just proof that I can get value of quantity" />
<input type="button" onclick="passData('test', 2, 2)" value="button passing the data" />

js: js:

function updateQuantity(ID, action){

var prodQty = document.getElementById(ID);
var maxQty = 3;

    if(action === 'add') { 
        prodQty.value++; 
        if(prodQty.value > maxQty) { prodQty.value = maxQty }

    } else { 
        prodQty.value--; 
        if(prodQty.value <= 0) { prodQty.value = 1 }
    } 
} 

function passData(p1, p2, p3) {
    alert('First: '+p1 + ', Second: ' + p2 +', Third: '+ p3);
}

function getUpdatedQty() {
    var prodQty = document.getElementById('test'); alert(prodQty.value);
}

I've found the solution, maybe someone else will need this in the future: 我已经找到了解决方案,也许将来有人会需要这个解决方案:

html: 的HTML:

<input type="text" name="quantity" id="test" value="1" />
<input type="button" onclick="updateQuantity('test','add')" value="+" />
<input type="button" onclick="updateQuantity('test','not')" value="-" />
<input type="button" onclick="passData('test', 2, getUpdatedQty)" value="button passing the data" />

js: js:

function updateQuantity(ID, action){
var prodQty = document.getElementById(ID);
var maxQty = 3;

        if(action === 'add') { prodQty.value++; 
            if(prodQty.value > maxQty) { prodQty.value = maxQty }

         } else { prodQty.value--; 
                if(prodQty.value <= 0) { prodQty.value = 1 }
         } 
    } 

    function passData(p1, p2, p3) {

    alert('First: '+p1 + ', Second: ' + p2 +', Third: '+ p3());
    }

function getUpdatedQty() {
    var prodQty = document.getElementById('test'); return prodQty.value;
}

jsFiddle jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM