简体   繁体   中英

Calling Javascript function multiple times

I have a Simple JavaScript Function:

function f1()
{
    alert("HI");
}

I'm calling the same Javascript function from two places, say:

<input type="submit" id="btn1" onclick="f1()"/>

<input type="submit" id="btn2" onclick="f1()"/>

How to find the target element which called this Function?

EDIT: How to check if the element is a button or some other?

HTML

<input type="submit" id="btn1" onclick="f1(this)"/>
<input type="submit" id="btn2" onclick="f1(this)"/>

Js

function f1(el) {
    console.log(el)
}

Demo: Fiddle

function f1(element)
{
    alert($(element).attr("id"));

    if ($(element).is(":button")) {
        alert("Im button");
    }
}

<input type="submit" id="btn2" onclick="f1(this)"/>

Try with this

<input type="submit" id="btn1" onclick="f1(this)"/>
<input type="submit" id="btn2" onclick="f1(this)"/>

and console like

function f1(comp)
{
    console.log(comp);
}

Add this to the function call

<input type="submit" id="btn1" onclick="f1(this)"/>

<input type="submit" id="btn2" onclick="f1(this)"/>

And modify your js as

function f1(el)
{
    alert(el.nodeName) ; // alerts type of HTML element
}

el will contain a reference to the element

EDIT : added code to detect type of HTML element

Easiest way:

<input type="submit" id="btn1" onclick="f1(this)"/>

<input type="submit" id="btn2" onclick="f1(this)"/>

JS:

function f1(btn)
{
    alert("Hi from " + btn);
}

If you are already using jquery on your page, maybe you should try giving all the elements that you want to target a shared class and then detect the clicks?

<input class="same_kind_buttons" type="submit" id="btn1" />
<input class="same_kind_buttons" type="button" id="btn2" />


<script> 
$(".same_kind_buttons").click(function() {
  console.log($(this).attr("type")); 
  console.log(this.id);
});
</script>

Of course if your'e not using jquery on the page you shouldn't include it just for that function and you can use :

<input type="submit" id="btn1" onclick="f1(this);"/>
<input type="submit" id="btn2" onclick="f1(this);" />

<script>
  function f1(elem) {
    console.log(elem.tagName);
    console.log(elem.id);
  }
</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