我在Rails页面上有以下jQuery:
$(document).on('click','.reportsArrow', function() { if ( $(this).parent().hasClass('reportCollapsed') ) { console.log("A"); $(this).parent().removeClass('reportCollapsed'); }else{ $(this).parent().addClass('reportCollapsed'); console.log("B"); } });当我点击具有reportsArrow且没有reportCollapsed的元素时,日志显示
B
A
这意味着它正在执行else部分,然后执行if部分。 我希望函数只能每次点击执行一次,并且只能遵循一个代码路径。 为什么它被执行两次,我该如何阻止? 我应该指出,这在网页设计师创建的模型中(仅在HTML / CSS / JS上)正确切换。 看起来问题是Rails相关的。
编辑:
我们找到了一个工作解决方案:
$('.reportsArrow').click(function() { $(this).parent().toggleClass('reportCollapsed'); });I have the following jQuery on a Rails page:
$(document).on('click','.reportsArrow', function() { if ( $(this).parent().hasClass('reportCollapsed') ) { console.log("A"); $(this).parent().removeClass('reportCollapsed'); }else{ $(this).parent().addClass('reportCollapsed'); console.log("B"); } });When I click on an element with reportsArrow and without reportCollapsed, the log shows
B
A
Meaning it is executing the else part and then executing the if part. I want the function to only be executed once per click, and to only follow one code path. Why is it being executed twice and how do I stop this? I should point out that this toggles correctly in the mockups created by the web designer (on HTML/CSS/JS only). It looks like the problem is Rails related.
EDIT:
We have found a working solution:
$('.reportsArrow').click(function() { $(this).parent().toggleClass('reportCollapsed'); });最满意答案
不知道为什么,但我在不引人注意的JavaScript的日子已经教会了我尽可能具体和尽可能模糊。
从不担心为什么,只要它有效。 被问及为什么(就在这里),我的回答是“我将不得不查看它”。 抱歉。
因此,我会避免在文档上设置catch方法,然后过滤操作:我会直接将事件捕获到要观看的元素(或元素集)上。
所以,而不是使用:
$(document).on('click','.reportsArrow', function() { //... });我会直接的方式:
$('.reportsArrow').click(function () { //.. });阅读jQuery .on()的API文档后,我觉得它可能更适合使用.one() ,所以在命中“#1”后没有延续。 但我没有测试过,所以我不能肯定地说。
Not sure why, but my days in unobtrusive javascript have taught me to be as specific and as least fuzzy as I can.
Never worried why, as long as it worked. Having been asked why (just here), my answer is "I will have to look it up". Sorry.
Thus, I would avoid setting a catch method on THE document and then filter actions: I would directly point the event catches on the element (or set of elements) I want to watch.
So, instead of using:
$(document).on('click','.reportsArrow', function() { //... });I would go the direct way:
$('.reportsArrow').click(function () { //.. });Having read the API documentation for jQuery .on(), it appears to me that it would be probably more suitable to use .one() instead, so there is no continuation after hit "#1". But I have not tested it, so I can't say for sure.
更多推荐
发布评论