简体   繁体   中英

How to handle onclick events from multiple dynamically created anchor tags using jquery/javascript?

I have multiple dynamically created anchor tags that work as buttons. When any of these buttons are clicked, I want to call a single javascript function that sits in another file, which will do the rest of the fun work. My problem is that I cannot properly call the function via the 'onclick' event, so I am trying to find a way around it but it's just not so simple for me.

I have tried many different ways so I understand a few limitations with this approach:

Standard HTML anchor with Javascript:

<a href=#" onclick="doSomething(parameter1, parameter2, ...);">Button</a>

This is not going to help because there are synchronization issues and I have found that href will be chosen above on click almost always I have found. I actually would love this way to work, if you know any workarounds here then please let me know.

Binding via JQuery:

$(document).ready(function() {
     $("#button_id").click(function() {
         doSomething(parameter1, parameter2, ...);
     });
});

My issue with binding is that when the page is loaded, I have a function that gets the data from the database and displays it in a list. Each list element has a button, which 'on click' will call a javascript function, passing it parameters according to whatever data I need to give it from the list element, and it then will do something.

I understand that in order for Binding to work well, each button should have its own ID so that its easy to associate them with the Binding method. However, I am not sure how to tell the the .click function how many ID's I have, nor how to give it these parameters (unless I capture them via button ID by calling other JS functions).

Any suggestions/ideas are highly appreciated!

EDIT: How do I go about adding the button_data to the parameters of the 'doSomething(parameter);' function?

list_element = '<span class="ui-li-count" data-mini="true">' + button_data + '<a href="#" class="my_button">Button</a>';</span>

Please remember this data is obtained dynamically from the database and posted onto the site when the page is first loaded.

There is no need to use an id for this. That's the opposite of what you need to be doing since you are giving a group of element identical functionality. Instead, you should be giving them a class to group them:

<a href=#" class="my-button">Button</a>

And the JavaScript:

$(document).ready(function() {
     $('body').on('click', '.my-button', function() {
         doSomething(parameter1, parameter2, ...);
     });
});

This will bind the click event to all .my-button elements, even ones that you haven't created yet. Replace body with the parent element that contains all of the buttons to make this work a bit faster.

Use the .on() function.

http://api.jquery.com/on/

You could also add a specific prefix to the id like test_<id> and then you can use wild card selectors:

$("[id^=test]").on('click', function () {
    doSomething();
});

Or, if like me, you prefer raw JS:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<script type="text/JavaScript">

function createAnchor( strParentElementId, strLinkText, strLinkHref, intArg1, intArg2 ) {

    var objAnchor   = null;
    var objParent   = document.getElementById( strParentElementId );
    var boolCreated = false;

    if ( objParent != null ) {

        objAnchor = document.createElement( 'A' );
        if ( objAnchor != null ) {

            with ( objAnchor ) {
                style.color = 'yellow';
                innerText   = strLinkText;
                href        = strLinkHref;
                onclick     = function() { doSomething( intArg1, intArg2 ); }
                } //with

            objParent.appendChild( objAnchor );

            boolCreated = true;
            } //if-create-element
       }  //if-get-parent

return boolCreated;
}

function doSomething( intArg1, intArg2 ) {
    alert( 'doSomething( ' + intArg1.toString() + ', ' + intArg2.toString() + ' );' );
return true;
}

</script>

<body>

<a name="hello">Hello</a><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

<a name="world">World!</a><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />


<div id="myDiv1" style="background-color:red;"></div><br />
<div id="myDiv2" style="background-color:red;"></div><br />


<script type="text/JavaScript">
createAnchor( 'myDiv1', 'Link 1 - Hello', '#hello', 1, 2 );
createAnchor( 'myDiv2', 'Link 2 - World', '#world', 3, 4 );
</script>

</body>
</html>

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