简体   繁体   中英

Set value of button clicked as a Javascript variable - without using an ID/Name

Is it possible for me to carry the value of a button over to the function that that the button executes?

Simple concept, how would I get the value "5" to be carried over to my function where I can define it as a variable?

<button onclick="functionHere()" value="5">Delete</button>

Code actually looks more like:

<button onclick="functionHere()" value="' + aData[5] + '">' + 'Delete</button>

In your example you can reference the button element using this.

HTML:

<button onclick="functionHere(this)" value="' + aData[5] + '">' + 'Delete</button>

JS:

function functionHere (btn) {
    var buttonValue = btn.value;
}

this references the context of the function. So in this case since the function was called by setting it as the onclick of the button, the functions context is the button element.

EDIT: I am mistaken actually this doesn't seem to be set automatically when used how you use it. Code updated. Here is a fiddle: http://jsfiddle.net/9nv4sz6L/

You can do it like this.

<input type="button" value='Hello World' onclick='ShowValue(this)'/>

<script>
    function ShowValue(btn){  
        alert(btn.value);
    }
</script>

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.

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