问题
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