admin管理员组文章数量:1346053
I want to pass an object to onclick function as parameter. Then I will call that parameter into the function and push into empty array. But I tried it all, it just push id, name etc. I want to pass laundryValue[i]
whole array on onclick="getLaundryClick()
as parameter.
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
]
var newLaundryValue = [];
for (var i in laundryValue) {
var wrap = laundryValue[i];
document.getElementById('laundry-value').innerHTML +=
'<li>' +
'<div class="laundry-name">' + laundryValue[i].name + '</div>' +
'<div class="laundry-price">' + laundryValue[i].price + '</div>' +
'<button class="laundry-btn" onclick="getLaundryClick(' + [wrap] + ')">' + 'Add' + '</button>' +
'</li>';
}
function getLaundryClick(wrap) {
console.log(wrap)
}
I want to pass an object to onclick function as parameter. Then I will call that parameter into the function and push into empty array. But I tried it all, it just push id, name etc. I want to pass laundryValue[i]
whole array on onclick="getLaundryClick()
as parameter.
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
]
var newLaundryValue = [];
for (var i in laundryValue) {
var wrap = laundryValue[i];
document.getElementById('laundry-value').innerHTML +=
'<li>' +
'<div class="laundry-name">' + laundryValue[i].name + '</div>' +
'<div class="laundry-price">' + laundryValue[i].price + '</div>' +
'<button class="laundry-btn" onclick="getLaundryClick(' + [wrap] + ')">' + 'Add' + '</button>' +
'</li>';
}
function getLaundryClick(wrap) {
console.log(wrap)
}
Share
Improve this question
edited Jul 5, 2020 at 5:26
Unmitigated
89.8k12 gold badges99 silver badges104 bronze badges
asked Jul 5, 2020 at 4:38
Ali AsgerAli Asger
631 silver badge7 bronze badges
6
- 1 you should pass an Id as parameter that makes reference to the object. that object might be stored in localstore then when you click on the function you can find the object using the Id searching into localstore. LocalStore is a global place to save data. – Bob White Commented Jul 5, 2020 at 4:46
- your console.log returns [object Object]? – José Commented Jul 5, 2020 at 4:47
-
@José Nope it say
Uncaught SyntaxError: Unexpected identifier
– Ali Asger Commented Jul 5, 2020 at 4:49 - if you are always going to have the object in memory I would pass an index only, otherwise I would pass JSON.stringify ([wrap]), although the latter is a bit dirty, in any case the correct form would be document.createElement and then to that add element in event listener – José Commented Jul 5, 2020 at 4:50
- onclick="getLaundryClick(' + JSON.stringify ([wrap]) + ')">' try this and in the function do parse – José Commented Jul 5, 2020 at 4:52
6 Answers
Reset to default 6You can use JSON.stringify
to convert the object to a string and use JSON.parse
in the onclick handler to convert it back.
'<button class="laundry-btn" onclick="getLaundryClick(JSON.parse(\''
+ JSON.stringify(wrap).replace(/'/g, ''').replace(/"/g, '"') + '\'))">'
+ 'Add' + '</button>'
Another option is just to play around with single and double quotes PAIR
so it would not conflict as we are passing here a quoted string, we need to consider how it is rendered as in it's HTML form:
Working Simplified Version:
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
]
var newLaundryValue = [];
for (var i in laundryValue) {
var wrap = laundryValue[i];
wrap = JSON.stringify(wrap)
document.getElementById('laundry-value').innerHTML +=
'<li>' +
'<div class="laundry-name">' + laundryValue[i].name + '</div>' +
'<div class="laundry-price">' + laundryValue[i].price + '</div>' +
'<button class="laundry-btn" onclick=\'getLaundryClick(' + wrap+' ) \'>' + 'Add' + '</button>' +
'</li>';
}
function getLaundryClick(wrap) {
console.log(wrap)
}
<div id="laundry-value">
</div>
Try this, I wrote the plete code. Here I just used the laundaryValue array for looping and stored it in a variable, then binded on html.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="laundry-value"></div>
<button onclick="getLaundryClick()">Get Laundary</button>
<script type="text/javascript">
let laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
]
let loopData = '';
function getLaundryClick(){
for (let i = 0; i < laundryValue.length; i++) {
let addObj = JSON.stringify(laundryValue[i]);
loopData +=
`
<ul>
<li>ID: ${laundryValue[i].id}</li>
<li>Name: ${laundryValue[i].name}</li>
<li>Price: ${laundryValue[i].price}</li>
<li><button onclick='addObjectFunction(${JSON.stringify(laundryValue[i])})'>Add</button></li>
</ul>
`;
}
document.getElementById('laundry-value').innerHTML = loopData;
}
function addObjectFunction(params){
console.log(params)
}
</script>
</body>
</html>
You can create a class to create buttons dynamically from an array by this way: You can set the print method inside this class to access any value of any element of your array.
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
];
class ButtonToPress {
constructor(obj) {
this.obj = obj;
const button = document.createElement('button');
button.onclick = this.print.bind(this);
button.innerText = this.obj.name;
document.getElementById('laundry-value').appendChild(button);
}
print() {
console.log(this.obj.name, this.obj.price);
}
}
let buttons = [];
for (let i = 0; i < laundryValue.length; i++) {
buttons[i] = new ButtonToPress(laundryValue[i]);
}
<div id="laundry-value"></div>
The above solutions with JSON.parse()
will work. However, you can achieve the same thing with less effort:
const laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20} ];
var newLaundryValue = [];
document.getElementById('laundry-value').innerHTML = laundryValue.map((wrap,i)=>
`<li><div class="laundry-name">${wrap.name}</div>
<div class="laundry-price">${wrap.price}</div>
<button class="laundry-btn" data-id="${i}">Add</button>
</li>`
).join('\n');
document.onclick=function(ev){ let el=ev.target; // global click handler ...
if (el.classList.contains('laundry-btn')){let itm=laundryValue[el.dataset.id];
newLaundryValue.push(itm)
console.log(`added ${itm.name} to cart.`)
} else if (el.classList.contains('cart'))
console.log(JSON.stringify(newLaundryValue));
}
li div {display: inline-block; margin:4px 8px}
<div id="laundry-value"></div>
<hr><button class="cart">show cart</button>
CASE 1
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
]
var newLaundryValue = [];
for (var i in laundryValue) {
var wrap = laundryValue[i];
var data = JSON.parse(JSON.stringify(wrap));
document.getElementById('laundry-value').innerHTML +=
'<li>' +
'<div class="laundry-name">' + laundryValue[i].name + '</div>' +
'<div class="laundry-price">' + laundryValue[i].price + '</div>' +
'<button class="laundry-btn" onclick="getLaundryClick(JSON.parse(\''
+ JSON.stringify(wrap).replace(/'/g, ''').replace(/"/g, '"') + '\'))">'
+ 'Add' + '</button>' +
'</li>';
}
function getLaundryClick(wrap) {
console.log(wrap);
}
<div id="laundry-value"></div>
CASE 2
See working example..
var laundryValue = [
{id: 1, name: 'Sunglasses', price: 25},
{id: 2, name: 'Jeans', price: 10},
{id: 3, name: 'Shirts', price: 15},
{id: 4, name: 'Cables', price: 20}
];
class ButtonToPress {
constructor(obj) {
this.object = obj;
const button = document.createElement('button');
button.onclick = this.print.bind(this);
button.innerText = this.object.name;
document.getElementById('laundry-value').appendChild(button);
}
print() {
console.log(this.object);
}
}
let buttons = [];
for (let i = 0; i < laundryValue.length; i++) {
buttons[i] = new ButtonToPress(laundryValue[i]);
}
button{
margin: 0 5px;
background: #0095ff;
border:none;
padding: 5px 10px;
border-radius: 5px;
}
<div id="laundry-value"></div>
本文标签: javascriptPassing object as a parameter on an onClick functionStack Overflow
版权声明:本文标题:javascript - Passing object as a parameter on an onClick function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743822393a2545023.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论