Jquery Toggle on click of image

时光毁灭记忆、已成空白 提交于 2019-12-12 18:23:07

问题


I am trying to understand how the jquery toggle works. I want to toggle to next anchor with class plr-anchor on click of image with class go_down. The data is populated using maps.

Jquery code:

$('.go_down').on('click',function(e){
    #('.plr-anchor').next('.plr-anchor').toggle()});
}

Code snippet:

{data.map(function(categ) {
return <div>
<a className="plr-anchor" id={categ.short_name}></a>
<img src="/static/img/icon_up.png" className="go_down"/>
</div>}.bind(this)}

There seems to be a problem with the syntax on the Jquery call function. I am newbie with Jquery, any help will be great. Thanks in advance.


回答1:


You have used # instead of $ inside click handler. Also you need to find exact plr-anchor which is before the clicked image. Right now you are toggling all plr-anchor.

For dynamic elements, use $(document).on(event, selector, function(){}); for binding click handlers. See below code

$(function(){
  $(document).on('click','.go_down',function(e){
     $(this).prev('.plr-anchor').toggle();
  });
});



回答2:


Your jQuery code has a "#" instead of a "$". By the way, React and jQuery don't always go together. The whole purpose of React is to use virtual dom and let React take care of dom updates. While jQuery is mostly about direct dom manipulation. What you are trying here will interfere with React because it won't expect the dom to change without the v-dom changing.

Ideally, you should be using event handlers and state in your component to toggle visibility.



来源:https://stackoverflow.com/questions/34348458/jquery-toggle-on-click-of-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!