문제

I'm trying to use the highlight effect from jQuery UI to show the user an explanation corresponding to some radio button choices. But the effect triggers twice, i.e. the relevant page component flashes twice instead of once.

I've had a look at similar questions, but they either have solutions that don't apply to my case or have a solution that doesn't work in my case. (Or the answers/comments ask for more details or an example which is never given.)

Here is a jsfiddle with a simplified version of my problem.

If you click on one of the radio buttons, the corresponding paragraph flashes green twice. As you can see from the JS section, the solution proposed in the second link above (using .off('click').on('click') to prevent the "cloning" effect) doesn't seem to make a difference.

I'm using jQuery 1.8.0 and jQuery UI 1.8.22 (jsfiddle uses 1.7.2 and 1.8.18, respectively, and has the same issue) and the same thing happens on Opera, Chrome, and Firefox.

How can I work around this and have the effect only execute once? Happy to use a workaround if there is one...

도움이 되었습니까?

해결책

The problem is that 2 click events are triggered, once for the label and once for the input. This is because a click on the label 'triggers' a click on the input. Change your selectors to prevent this:

    $('#labelChoice1 input').click(function(e) {
        highlightDiv(1);
    });
    $('#labelChoice2 input').click(function(e) {
        highlightDiv(2);
    });

Here's the updated fiddle.

다른 팁

A more extensible version might look like this:

function highlightDiv(index) {
    $('p#explanation' + index).effect("highlight", {color: '#00ff00'}, 1000);
}

$(':radio').each(function(i) {
    $(this).click(function() {
        // zero-based index
        highlightDiv(i + 1);      
    });
});
​

http://jsfiddle.net/a7kRB/5/

this seems to work just fine

$('#labelChoice2').on('click', '#choice2', function() {
    highlightDiv(2);
});

the second parameter basically just says on which sub children of #labelChoice2 the method should apply, trying it on jsfiddle shows that this solution works

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top