简体   繁体   中英

make a div inside a list item clickable

I am working on a project to display a bookmarks page and part of what I want to do is keep the description and toggle features for each bookmark hidden until the bookmark is clicked. I want to keep it simple with an add/removeClass() to decide if the rest of the bookmark-info is showing. I also want to only allow one to be open at a time but before I can do that I need my bookmarks clickable first.

I've started with making the bookmark-titles a button but would like to change it from this for styling purposes.

I'm not calling upon the bookmark correctly because it won't console.log anything on the bookmark button click. Take a look keeping in mind im only including 2 functions of my code. I declare for the content to be added later and I call the functions at the bottom of my js:

 const generateItemElement = function (item) { //item is the definition of the current object and all let itemTitle = `<span class="bookmark bookmark_filtered">${item.title}${item.rating}</span>`; //affects filtered items //REMEMBER TO ADD DELETE FUNCTION AND ICON return ` <li class="js-bookmark" data-item-id="${item.id}"> <button type='button' class="js-bookmarkHead"> ${itemTitle} </button> <div id="js-bookmarkInfo" class='hidden'> <button class="js-item-delete">Delete</button> <button class="visit"> <a href="${item.url}"target=blank>Visit</a> </button> <div class="description"> ${item.desc} </div> </div> </li>`; }; const handleToggleExpandClick = function () { $('#bookmarkHead').click(() => { $('#js-bookmarkInfo').removeClass('hidden'); render(); }); };

This line:

$('#bookmarkHead').click(() => {

Sets up the click-handler which needs to be done after the bookmark elements have been added to the DOM, so the way your code is structured right now, you would have to call handleToggleExpandClick after generateItemElement . Check out delegated event handlers in order to workaround this issue.

However, the selector you have specified $('#bookmarkHead') is incorrect, it should be $('.js-bookmarkHead') since you're using the class attribute. Also, id attributes have to be unique and I'm guessing you have multiple bookmarks so I would not use that attribute for js-bookmarkInfo .

You could also change your click handler to something like:

$('.js-bookmarkHead').click(function() { // <- not using arrow style signature
  // $(this) will refer to the clicked .js-bookmarkHead element
  $(this).next().toggleClass('hidden');
  render();
});

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