0

I'm receiving an ajax response, and based on this adding some html content to the dom.

Problem: I want to also add a link that should have a onclick function with passing a parameter from the response.

Example: http://jsfiddle.net/zu1ymrh8/55/

<a class="LoadFromAjax" href="#">Load Ajax</a>
<div class="appendedContainer"></div>


$(function() {
  function myfunc(input) {
    alert("test: " + input);
  }
  
  $(".LoadFromAjax").on("click", function() {
      event.preventDefault();

      $.ajax({
        url: 'https://dog.ceo/api/breeds/list/all',
        type : 'get',
        complete : function( qXHR, textStatus ) {
            var mock = "John"; //some values extracted from rsp

            $('.appendedContainer').hide();
            $('.appendedContainer').append(`<a href='#' onclick='myfunc(${mock})' class='mylink'>Alert me</a>`);
            $('.appendedContainer').fadeIn();
          }
      });
  });

});

Result: ReferenceError: myfunct is not defined. Why?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 2
    The error is because `myfunc()` is declared within the jQuery document.ready handler, not at global level. Use a [delegated event handler](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) instead – Rory McCrossan Oct 06 '21 at 15:08
  • But how can I pass a parameter to a delegate event handler? – membersound Oct 06 '21 at 15:09
  • @RoryMcCrossan Yes you are right. – Sparrow Oct 06 '21 at 15:10
  • @membersound Please wait I will write all possible way to do this. – Sparrow Oct 06 '21 at 15:11
  • Sorry unable to answer to this question. – Sparrow Oct 06 '21 at 15:17
  • 1
    @membersound put the `mock` value in a `data` attribute on the element, then read it back out in the delegated event handler: https://stackoverflow.com/a/5309947/519413 – Rory McCrossan Oct 06 '21 at 15:20
  • 1
    @RoryMcCrossan thank you so much, that was the missing piece in that puzzle. So passing a parameter directly is not possible, but setting the `data-` attribute and read it in the event handler works using `$(this).data("myparam")`! Unfortunately my question is locked so I cannot accept your solution. – membersound Oct 07 '21 at 07:53

2 Answers2

0

I suggest setting the click listener on the container element.

See example below

document.querySelector('button').addEventListener('click', load);
const container = document.querySelector('.container');

// delegating the click handler to the container
container.addEventListener('click', handleItemClick);

function load() {

 Promise
  .resolve(Date.now())
  .then(entry => {
    const child = document.createElement('a');
    child.innerText = entry;
    container.append(child);
  })
}


function handleItemClick(ev) {
  console.log(ev.target.innerText)
}
a {
  display: block;
}
<button>Load</button> 
<div class="container"></div> 
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22
0

How about something like:

$.ajax({
  ...,
  complete : function( qXHR, textStatus ) {
    var mock = "John"; //some values extracted from rsp

    // create a link:
    var link = $('<a>', {
      href : "the-url",
      class : "the-class",
    });

    // append to container:
    $('.appendedContainer').append(link);
            
    // set on click function:
    link.click(function() {

      // do something with mock:
      console.log(mock);

    });
             
    ...

  }
});
Daniel
  • 3,228
  • 1
  • 7
  • 23