如何在onclick上将参数传递给javascript函数?

时间:2015-11-20 10:26:55

标签: javascript jquery

我有一个脚本,我想通过传递参数调用onclick上的另一个函数。我想调用remove_product函数。我怎么能实现这个?

function load_cart(){
$('.mini-cart-products').html('');
var url = $('.ajax-url').attr('href');
var t   = 0;
// console.log(url);
$.ajax({
    url     : url,
    dataType:'json',
    success:function(result){

        if(result.length > 0)
        {
            var image       = $('.mini-cart-image a img');
            var prod_name   = $('.mini-cart-name a');
            var attribute   = $('.mini-cart-attributes');
            var pricing     = $('.mini-cart-pricing');

            $.each(result, function(key, val){

                var remove_url = val.remove;
                var barcode = val.barcode;
                var cart_id = val.cart_id;
                console.log("remove_url :"+remove_url+" barcode : "+barcode+" cart_id : "+cart_id);
                var productDiv  = $( "<div class='mini-cart-product clearfix'></div>" );                                             
                var nameDiv     = '<div class="mini-cart-name font"><a href="'+val.link+'">'+val.name+'</a></div>';
                var attributes  = $( "<div class='mini-cart-attributes'></div>" );
                var colorAttr   = '<div class="attribute"><span class="label">Colour: </span><span class="value">'+val.color+'</span></div>';
                var sizeAttr    = '<div class="attribute"><span class="label">Size&nbsp&nbsp&nbsp: </span><span class="value">'+val.size+'</span></div>';
                var remove  = '<div class="mini-cart-remove"><a onclick="remove_product(remove_url,barcode,cart_id)">Remove</a></div>';

4 个答案:

答案 0 :(得分:2)

remove var的行应该是这样的。

var remove  = '<div class="mini-cart-remove"><a onclick="remove_product(\''+remove_url+'\',\''+barcode+'\',\''+cart_id+'\')">Remove</a></div>';

这将解决您的问题

<强> Sample fiddle

答案 1 :(得分:0)

您应该在javascript代码的顶部声明一个成员变量。

<script>

var remove_product = null;

function yourFunction () {
  remove_product = 'your_value';
}

$("#yourButton").on('click', function (event) {

 alert(remove_product);

}


</script>

答案 2 :(得分:0)

你可以使用html onclick:

<button onclick="myFunction(param1, param2)">Click me</button>

或通过jQuery

$(button).on('click', function() {
     myFunction(param1, param2);
});

答案 3 :(得分:0)

这与其他答案相同,但没有jquery:https://jsfiddle.net/7L5ypo2r/

var testButton = document.getElementById('test-button')

testButton.onclick = function(){
  //your code would go here
    alert("test");
};