When I click the button it preforms a function, I am now trying to make it so name: "", is entered when the button is pressed.
I added name="item1" inside the tag but this does not yield the desired result.
<img onclick="addbeat()" name="item1" src="button.png"/> <script> function addbeat() { simpleCart.add({ name: "", price: .99 }); } </script>
You're using an event, so you can use the this
keyword.
simpleCart.add({
name: this.name,
price: .99
});
Also, I highly suggest moving away inline events. It's messy and leads to unreadable code. Use an event handler!
var x = document.getElementById("imgTag"); //add id to HTML element
x.addEventListener("click", addbeat, false);
Update for clarity
You have 2 options here. If you're going with an inline event handler, then you can pass an event object to your click handler and access the image that was clicked using event.target
, like so:
<img onclick="addbeat(event)" name="item1" src="button.png"/>
<script>
function addbeat(event) {
simpleCart.add({
name: event.target.name,
price: .99
});
}
</script>
A preferable option (as pointed out in surrounding discussion) would be to programmatically attach your click handler- at which point you could use either event.target
or this
.
<img id="anImage" onclick="addbeat(event)" name="item1" src="button.png"/>
<script>
function addbeat() {
simpleCart.add({
name: this.name,
price: .99
});
}
document.getElementById('anImage').onclick = addbeat;
</script>
I'm not sure if I understood your question, but:
<img onclick="addbeat(this.name)" name="item1" src="button.png"/>
<script>
function addBeat(name)
{
simpleCart.add({
name: name,
price: .99
});
}
</script>
Does this help?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.