2014-09-21 4 views
0

버튼을 클릭하면 팀 구성원 목록에서 선장을 선택할 수있는 코드를 작성하려고합니다. 버튼을 클릭하면 가능한 팀 구성원 (테이블에 배치)이 색을 변경 한 다음 그 중 하나를 클릭하면 새로운 선장으로 지정됩니다. 화면의 다른 곳을 클릭하면 팀 구성원이 정상적인 색으로 돌아가고 페이지가 정상으로 되돌아 가도록하고 싶습니다.jquery의 if/else 문으로 혼동 됨

Here은 내 시도를위한 피들입니다. 보시다시피, 작동하지 않습니다.

<table> 
    <tr> 
     <td class="name">John Smith</td><td class="captain"></td> 
    </tr> 
    <tr> 
     <td class="name">Smith Johnson</td><td class="captain"></td> 
    </tr> 
    <tr> 
     <td class="name">Joth Smithson</td><td class="captain"></td> 
    </tr> 
</table> 
<div id="button">C</div> 

그리고 내 JS는 다음과 같습니다 :

내 HTML은

$('#button').click(function() { 
    var people = $('table tr') 
    people.css('background-color','red'); 
    people.find('td.captain').html(''); 
    $('html').click(function(event) { 
     var target = $(event.target); 
     if($('table tr').has(target).length) { 
      var newcaptain = $('table tr').has(target); 
      newcaptain.find('td.captain').html('C'); 
      people.css('background-color',''); 
      $('html').off('click'); 
     } else { 
      people.css('background-color',''); 
      $('html').off('click'); 
     } 
    }); 
}); 

정말로 나를 당혹 것은 내가 다른 절에서 문을 제거하면 경우 부분은 I로 작동한다는 것입니다 그것을 의도했다. 이것이 어떻게 가능한지?

+1

조건부의 양쪽에 동일한 코드 줄을 넣는다면,이 줄은 처음부터 조건부 일 필요는 없습니다. 즉,'people.css ('background-color', ''); $ ('html'). off ('click');''if '결과에 상관없이 항상 실행됩니다. 무의미한. – Sparky

+0

예, 공정한 의견, 감사합니다. – lac

답변

0

이것은 event bubbling입니다. #button 클릭 메소드가 완료된 후 루트 요소에 도달 할 때까지 브라우저가 DOM 계층 구조 위로 올라와 다른 click 이벤트를 찾습니다. html 태그에 클릭 이벤트를 추가하기 때문에 브라우저는이를 발견하고 실행합니다. 그리고 tr (버튼을 클릭 함)을 클릭하지 않았으므로 else 문이 실행되고 css가 실행 취소됩니다.

만약 당신이 단지 $('html).click 전에 경고를 추가하면 쉽게 알 수있다 : 당신은 당신의 버튼 코드가 ​​작동했다고 볼 수

$('#button').click(function() { 
    var people = $('table tr') 
    people.css('background-color','red'); 
    people.find('td.captain').html(''); 
    alert('button click'); 
    $('html').click(function(event) { 
     var target = $(event.target); 
     if($('table tr').has(target).length) { 
      var newcaptain = $('table tr').has(target); 
      newcaptain.find('td.captain').html('C'); 
      people.css('background-color',''); 
      $('html').off('click'); 
     } else { 
      people.css('background-color',''); 
      $('html').off('click'); 
     } 
    }); 
}); 

,하지만 당신은 경고를 닫을 때 그것은 바로 돌아갑니다.

버튼 클릭 후 이벤트 버블 링을 중지해야합니다. 버튼 이벤트를 클릭하면 http://jsfiddle.net/jsfnvwvz/7/

+0

훌륭함, 고맙습니다. 그런 종류의 문제는 나에게 일어나지도 않았다. 도와 주셔서 감사합니다. – lac

0

:이를 추가하여 바이올린을 업데이트 한

$('#button').click(function(event) { 
    event.stopPropagation(); 
    var people = $('table tr') 
    people.css('background-color','red'); 
    people.find('td.captain').html(''); 
    $('html').click(function(event) { 
     var target = $(event.target); 
     if($('table tr').has(target).length) { 
      var newcaptain = $('table tr').has(target); 
      newcaptain.find('td.captain').html('C'); 
      people.css('background-color',''); 
      $('html').off('click'); 
     } else { 
      people.css('background-color',''); 
      $('html').off('click'); 
     } 
    }); 
}); 

:이 작업을 수행하는 가장 쉬운 방법은 false를 반환, 또는 버블 링 중지 브라우저에 지시 event.stopPropogation();를 호출하는 것입니다 모든 부모 레이어 (body, html, document)에도 전송됩니다.

$('#button').click(function(event) { 
    event.stopPropagation(); 
    ... 
} 

fiddle :

이 사용 event.stopPropagation()을 방지하기!