简体   繁体   中英

JQuery - how to append a dynamic href and use onclick?

I combined many things from what I read in forums and here is what I got so far:

$(document).ready(function () {
    $('input[name=key]').keyup(performUsernameAjax).focusin(performUsernameAjax);
    $('#users').click(function (event) {
        console.log('hello');
        event.preventDefault();
        console.log($(this).text());
        var dataStr = {
            'username': $(this).text(),
            'method': 'userdata'
        };
        var base_url = '<?= base_url() ?>';
        var url = base_url + 'login/userdata';
        console.log(url);
        $.ajax({
            type: 'POST',
            data: dataStr,
            dataType: 'json',
            url: url,
            success: function (data) {
                $("#userInfo").append("<p><ul><h3> " + data.username + "'s Info:</h3>");

                $("#userInfo").append('<li> The username: ' + data.username + '</li>');
                $("#userInfo").append('<li> The full name: ' + data.fullname + '</li>');
                $("#userInfo").append('<li> The num of failed logins: ' + data.failedlogin + '</li>');

                $("#userInfo").append('</ul></p>');
            }
        });
        return false; //for good measure
    });
});

//part of the performUsernameAjax function

for (var i = 0; i < data.length; i++) {
   console.log(data[i].username);
   $("#usernameList").append("<p><a href='#' id='users'>" + data[i].username + "</a></p>");
}

HTML :

<div class="field-info" id="usernameList"> </div>
<br>
<p><div class="field-info" id="userInfo"> </div></p>
<p><a href="#" id="users">rotemel</a></p>

The "for" loop is supposed to create a list of hyperlinks with usernames and I want that whenever a link is clicked the "click" listener will "catch" it and will do whatever I do there.. But it doesn't work so I tried few things: when I append a link in the "for" loop like that:

$("#usernameList").append("<p><a href='http://www.google.com' id='users'>" +
                            data[i].username + "</a></p>");

the link itself works fine - it redirects to the google page but when I do this:

$("#usernameList").append("<p><a href='#' id='users'>" +
                            data[i].username + "</a></p>");

because I want it to go to the "click" listener function that I've created, it does nothing... I thought perhaps that it might be the "click" listener function's fault so I added in the html file:

<p><a href="#" id="users">rotemel</a></p>

and it worked perfectly! So I'm just lost... what is the problem with my append or my href?? Thanks in advance!

There are two problems:

  1. use class="users" instead of id="users" as the id is specified to one elemnt not a group of elements.
  2. You are initializing onClick function on document ready. You have to move it to a separate function and call it both on DOM ready (if there are links at start) and also call it as Ajax callback function (To make effect on recently created links)

     $(document).ready(function () { $('input[name=key]').keyup(performUsernameAjax).focusin(performUsernameAjax); initializeOnClick(); }); function initializeOnClick(){ //Change #users to .users $('.users').click(function (event) { console.log('hello'); event.preventDefault(); console.log($(this).text()); var dataStr = { 'username': $(this).text(), 'method': 'userdata' }; var base_url = '<?= base_url() ?>'; var url = base_url + 'login/userdata'; console.log(url); $.ajax({ type: 'POST', data: dataStr, dataType: 'json', url: url, success: function (data) { $("#userInfo").append("<p><ul><h3> " + data.username + "'s Info:</h3>"); $("#userInfo").append('<li> The username: ' + data.username + '</li>'); $("#userInfo").append('<li> The full name: ' + data.fullname + '</li>'); $("#userInfo").append('<li> The num of failed logins: ' + data.failedlogin + '</li>'); $("#userInfo").append('</ul></p>'); } }); return false; //for good measure }); 

and later in your ajax function, again call that function:

   $.ajax({
   //blah blah

   ,success: function(result){
        //Your loop
        $("#usernameList").append("<p><a href='http://www.google.com' class='users'>" +data[i].username + "</a></p>");
        //End of loop

        //setup onclick on recently added items:
        initializeOnClick();
    }

})

You can't take id="users" more then one time in a document. try to increment your id with your var i.

Instead of

$('#users').click(function (event) {
}

Try

<a href="javascript:void callMe(cnt);" .. > </a>

change this

var dataStr = {
        'username': $(this).text(),
        'method': 'userdata'
};

With

var dataStr = {
        'username': $('#users'+cnt).text(),
        'method': 'userdata'
};

Like @Ali mentioned use class instead of id . The code should be like

$("#usernameList").append("<p><a href='#' class='users'>" +
                        data[i].username + "</a></p>");

Also, for event handler issue, the click handler will not work on future elements ie, newly appended elements after the DOM was ready. We have use delegate concept here

Replace the existing code

$('#users').click(function (event) {

with

$("#usernameList").on('click', '.users', function(event) {

Here the click has been delegated using on method.

Note: on method works with jQuery 1.7+ versions.

Hope this solves your requirement!

So thank you everyone! You were right about the fact that I was initializing onClick function on document ready that's why it didn't work.. (Also I was wrong to use id instead of class) So I tried looking up about that subject and found this question:

jQuery onclick not firing on dynamically inserted HTML elements?

and I did what the answer there said with the #wrapper and that solved my problem! So thanks!

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