简体   繁体   中英

jQuery On-click event not working as intended

I'm working on a project that returns GIFs from the GIPHY API, and whenever a search is executed, I'm capturing each search history item as its own button that a user can click on and see the results of the search as opposed to retyping the search again. I successfully added the buttons to the HTML with the proper classes, however, when I tried to write a simple on click event such as $('.history-btn').on('click', function() { console.log('hello'); }); nothing appears. What is causing this? Here is my whole set of code for context:

 $(document).ready(function () { var searches = []; function addSearch() { $(".prev-searches").empty(); for (var i = 0; i < searches.length; i++) { var history = $('<button>'); history.addClass("btn btn-primary history-btn"); history.attr("data-name", searches[i]); history.text(searches[i]); $(".prev-searches").append(history); } } $('.history-btn').on('click', function() { console.log('hello'); }); function returnSearch() { var gifSearch = $(".search-input").val().trim(); var queryURL = 'https://api.giphy.com/v1/gifs/search?api_key=XXXXX-HIDDEN-XXXXX&q=' + gifSearch + '&limit=15&offset=0&rating=PG&lang=en'; $.ajax({ url: queryURL, method: "GET" }).then(function(response){ console.log(queryURL); console.log(response); console.log(response.data.length); for (var i =0; i < response.data.length; i++) { arrImg = response.data[i].images.fixed_width.url; var newContent = ''; newContent = '<img src="' + arrImg + '">'; $('.gif-area').html(newContent); console.log(newContent); } }); } //When search is executed $('.search-btn').on('click', function() { event.preventDefault(); var search = $('.search-input').val().trim(); searches.push(search); addSearch(); returnSearch(); }); function renderGIFs () { for (var i = 0; i < response.data.length; i++) { var newGifs = ''; newGifs += '<img src="' + response.data[i].bitly_gif_url + '"'; $(".gif-area").html(newGifs); } } }); 

You need event delegation:

$('.prev-searches').on('click', '.history-btn', function() {
    console.log('hello');
});

Resource

Is the class 'history-btn' added dynamically from your addSearch function? Then please use an element which is above in heirarchy of history-btn and bind the event to that element.

For example I bind the event to the div element,

<div id='historybtncontainer'>
    <button class='history-btn'>Button</button>
</div>

and in script you can do

$('historybtncontainer').on('click', 'history-btn', function(){
    console.log("hello");
});

document allows you to get a new tree of elements after dynamically adding the history-btn class to the <button>

$(document).on('click', '.history-btn', function() {
console.log('hello');
});

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