简体   繁体   English

Javascript-如何在onclick事件中将数组作为参数传递?

[英]Javascript- How to pass array as parameter at onclick event?

I have an array that I want to pass to a javascript onclick function. 我有一个数组,我想传递给javascript onclick函数。 I send that array in the onclick event of a button. 我在按钮的onclick事件中发送该数组。 The onclick function return me [object Object]. onclick函数返回我[object Object]。 Is there a different way to do call that function with the array? 是否有不同的方法来调用该函数与数组?

Here My Code: 我的代码:

var data_type= $.parseJSON(data_playtype[1]);//{"1":"apple","2":"orange","23":"berry","8":"grape","9":"mango"}


str1.push('<td><a href="javascript:void(0)" onClick="showABC(\''+data_type+'\')">'Data'</td>');



function showABC(fruit){

    $.each(fruit,function(pid,pt){
        alert(pt);
    });

}

I have an array that I want to pass to a javascript onclick function. 我有一个数组,我想传递给javascript onclick函数。 I send that array in the onclick event of a button. 我在按钮的onclick事件中发送该数组。 The onclick function return me [object Object]. onclick函数返回我[object Object]。 Is there a different way to do call that function with the array? 是否有不同的方法来调用该函数与数组?

Note, data_type not appear to be Array at js ; 注意, data_typejs看起来不是Array ; data_type appear to be Object data_type似乎是Object


Try utilizing .on() , calling showABC() within click event handler with data_type as parameter. 尝试使用.on() ,在click事件处理程序中调用showABC() ,并将data_type作为参数。

 var data_playtype = []; data_playtype[1] = JSON.stringify({ "1": "apple", "2": "orange", "23": "berry", "8": "grape", "9": "mango" }); var data_type = $.parseJSON(data_playtype[1]); //{"1":"apple","2":"orange","23":"berry","8":"grape","9":"mango"} var str1 = []; str1.push("<td><a href=javascript:void(0)>Data</a></td>"); function showABC(fruit) { $.each(fruit, function(pid, pt) { alert(pt); }); }; $("table tbody").append(str1).find("a") .on("click", function() { showABC(data_type) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody></tbody> </table> 

DEMO DEMO

Using inline JS is not a good idea. 使用内联JS不是一个好主意。 I would use a data attribute to hold the data as follows: 我会使用data属性来保存数据,如下所示:

var data_type = .....;
var link = $('<a/>').data('data_type', data_type).html('Data');
str1.push( $('<td/>').html( link ) );

//event handler
link.on('click', function(e) {
    e.preventDefault();
    var data_type = $(this).data('data_type');
    .....
});

Ref: https://api.jquery.com/data/ 参考: https//api.jquery.com/data/

.data( key, value ) .data(键,值)

key

Type: String A string naming the piece of data to set. 类型:String一个字符串,用于命名要设置的数据。

value

Type: Anything The new data value; 类型:任何新数据值; this can be any Javascript type except undefined . 这可以是除undefined之外的任何Javascript类型。

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

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