2014-04-22 3 views
2

현재 뉴스 피드와 같은 "유사한"시스템을 위해 일하고있을 때, 1 페이지에 여러 개의 뉴스 피드가 있습니다. 이는 동일한 ID를 가진 버튼이 여러 개 있음을 의미합니다.동일한 ID를 가진 HTML 요소

$(document).ready(function(){ 
    $('#likebutton').click(function(){ 
     $.ajax({ 
      url : 'inc/ajax.php', 
      type : 'POST', 
      data : { 
       action : 'like_post', 
       poid : $('#likebutton').data('poid') 
      }, 
      dataType : 'JSON', 
      success : function(result) { 
       if (result.xhr == 'success') { 
        $('#likebutton').attr('disabled','true'); 
        $('#likes').html(parseInt($('#likes').html()) + 1); 
       } else if (result.xhr == 'error'){ 
        alert('An internal error occurred, try again later.') 
       } 
      } 
     }); 
    }); 
    $('#unlikebutton').click(function(){ 
     $.ajax({ 
      url : 'inc/ajax.php', 
      type : 'POST', 
      data : { 
       action : 'unlike_post', 
       poid : $('#unlikebutton').data('poid') 
      }, 
      dataType : 'JSON', 
      success : function(result) { 
       if (result.xhr == 'success') { 
        $('#unlikebutton').attr('disabled','true'); 
        $('#likes').html(parseInt($('#likes').html()) - 1); 
       } else if (result.xhr == 'error'){ 
        alert('An internal error occured, try again later.') 
       } 
      } 
     }); 
    }); 
}); 

모든이가 같은 버튼을 비활성화하고 카운터에 1을 추가 할 수있는 지점까지 잘 작동 : 이 내가 게시물을 좋아하는 데 사용하는 JQuery와 있습니다. 그것이하는 일은 그 페이지에있는 모든 버튼을 사용할 수 없게 만들고 페이지를 새로 고쳐 다른 게시물을 좋아해야합니다. 나는 동일한 ID를 가지고있는 HTML 요소가 두 개 이상 있기 때문에 고유 ID를 제공 할 수 없다는 것을 알고 있습니다. 왜냐하면 포스트와 자바 스크립트를 반향시키는 함수가 다른 페이지에 있고 또한 고유 ID를 만들면, 이 페이지 (10)의 모든 게시물에 대해이 기능을 반복해야합니다.

편집 :

관련 HTML

<div class='media-body'> 
    <h4 class='media-heading'>post #1</h4> 
    <p>post #1</p> 
    <button data-poid="10" class="btn btn-link btn-xs likebutton" style="font-size: 14px;"><i class="fa fa-thumbs-up"></i> <small>Like</small> 
    </button> 
    <h5 id='likes' style="display: inline;">0</h5> <small>likes</small> 
    <small style="cursor:pointer;" onClick="$('#comments10').toggle('slow');">Add Comment</small> 
    <form action="" method="post" id="comments10" style="display:none;"> 
     <input type="hidden" name="id" value="10"> 
     <textarea style="width:100%;height:100px;" name="comment"></textarea> 
     <br /> 
     <input type="submit" class="btn btn-primary" value="Add comment" /> 
    </form> 
</div> 

내가 ... 내가 일을 모든 사람의 시간과 @의 satapal의 답변을 낭비 미안 잘못된 페이지를 편집 가장 큰 바보를 생각했다 편집 감사합니다 흠뻑!

+3

대신 ID를 사용하는 클래스를 사용하는 것이 좋습니다. –

+2

두 요소가 동일한 ID를 가질 수 없습니다 – Reeno

+0

@ReCaptcha 그리고 어떻게 그럴 수 있습니까? 제 스크립트를 사용하여 예제를 보여 주시겠습니까? –

답변

3

ID는 HTML에서 고유해야합니다. HTML 문서가 이 아닙니다.

중복 ID 대신 클래스를 사용하는 것이 좋습니다.

당신은 class selector

설명를 사용하여 클래스와 요소를 선택할 수 있습니다 : 지정된 클래스와 모든 요소를 ​​선택합니다.

구문

jQuery(".class") 

경우

클래스 : 클래스는 검색합니다. 요소는 여러 클래스를 가질 수 있습니다. 그 중 하나만 일치해야합니다.이

업데이트 HTML 당으로, 당신은 대신

var likes = $(self).parent().find('.likes'); 
likes.html(parseInt(likes.html()) - 1); 

을 사용해야합니다

수정 된 코드

$(document).ready(function() { 
    $('.likebutton').click(function() { 
     var self = this; 
     $.ajax({ 
      url: 'inc/ajax.php', 
      type: 'POST', 
      data: { 
       action: 'like_post', 
       poid: $(self).data('poid') 
      }, 
      dataType: 'JSON', 
      success: function (result) { 
       if(result.xhr == 'success') { 
        $(self).attr('disabled', 'true'); //Here I have used self 
        $('#likes').html(parseInt($('#likes').html()) + 1); 
       } else if(result.xhr == 'error') { 
        alert('An internal error accoured, try again later.') 
       } 
      } 
     }); 
    }); 
    $('.unlikebutton').click(function() { 
     var self = this; 
     $.ajax({ 
      url: 'inc/ajax.php', 
      type: 'POST', 
      data: { 
       action: 'unlike_post', 
       poid: $(self).data('poid') 
      }, 
      dataType: 'JSON', 
      success: function (result) { 
       if(result.xhr == 'success') { 
        $(self).attr('disabled', 'true'); //Here I have used self 
        $('#likes').html(parseInt($('#likes').html()) - 1); 
       } else if(result.xhr == 'error') { 
        alert('An internal error accoured, try again later.') 
       } 
      } 
     }); 
    }); 
}); 

편집하면 클래스를 사용하는 방법을 예를 제공합니다

$('#likes').html(parseInt($('#likes').html()) - 1); //Use +1 for like and -1 for unlike 
+0

@downvoter atremast comment – Satpal

+0

클래스가 btn btn-primary btn-xs likebutton과 비슷한 경우이 작업이 가능합니까? –

+0

내가 그것에 대해 생각하는 것을 기다리 자. 마찬가지로 카운터도 고유하지 않습니다.이 스크립트가 카운터와 똑같이 증가하도록하려면 어떻게해야합니까? –

0

동일한 페이지에서 동일한 ID를 두 번 이상 사용하면 안됩니다. 그것이 ID라고 불리는 이유입니다. :) 대신 클래스를 사용하고 jQuery에서 this 키워드를 사용하여 클릭 된 요소의 속성에 액세스하십시오.예 :

$('.likebutton').click(function(){ 
    $.ajax({ 
     url : 'inc/ajax.php', 
     type : 'POST', 
     data : { 
      action : 'like_post', 
      poid : $(this).data('poid') 
     }, 
     dataType : 'JSON', 
     success : function(result) { 
      if (result.xhr == 'success') { 
       $(this).attr('disabled','true'); 
       $('#likes').html(parseInt($('#likes').html()) + 1); 
      } else if (result.xhr == 'error'){ 
       alert('An internal error accoured, try again later.') 
     } } 
    }); 
}); 
0

거의 동일한 코드를 사용하고있는 것처럼 보입니다. 일을 예를 들어, 이전에 권장 그럼 당신은 클래스 선택기를 사용할 수 있습니다

var createLikeHandler = function (action, buttonSelector, counterSelector) { 
    return function() { 
     $.ajax({ 
      url : 'inc/ajax.php', 
      type : 'POST', 
      data : { 
       action : action + '_post', 
       poid : $(buttonSelector).data('poid') 
      }, 
      dataType : 'JSON', 
      success : function(result) { 
       if (result.xhr == 'success') { 
        $(buttonSelector).attr('disabled','true'); 
        var increment = action === 'like' ? 1 : -1 
        $(counterSelector).html(parseInt($(counterSelector).html()) + increment); 
       } else if (result.xhr == 'error'){ 
        alert('An internal error accoured, try again later.') 
      } 
     } 

    } 
}; 

같은 일을 더 재사용 확인하고 생성을 자동화

var likeUI = [{ 
    like: '.like1', 
    unlike: '.unlike1', 
    counter: '.counter1' 
}, 
{ 
    like: '.like2', 
    unlike: '.unlike2', 
    counter: '.counter2' 
}]; 

likeUI.forEach(function (likeElement) { 
    $(likeElement.like).click(createLikeHandler('like', likeElement.like, likeElement.counter)); 
    $(likeElement.unlike).click(createLikeHandler('unlike', likeElement.unlike, likeElement.counter)); 
}); 
1

당신은의 범위에 .likes를 확인 할 수 부모 :

$(document).ready(function(){ 
    $('.likebutton').click(function(){ 
     var self = this; 
     $.ajax({ 
      url : 'inc/ajax.php', 
      type : 'POST', 
      data : { 
       action : 'like_post', 
       poid : $(self).data('poid') 
      }, 
      dataType : 'JSON', 
      success : function(result) { 
       if (result.xhr == 'success') { 
        $(self).attr('disabled','true'); 
        $($(self).parent()).find('.likes').html(parseInt($($(self).parent()).find('.likes').html()) + 1); 
       } else if (result.xhr == 'error'){ 
        alert('An internal error occurred, try again later.') 
       } 
      } 
     }); 
    }); 
    $('.unlikebutton').click(function(){ 
     var self = this; 
     $.ajax({ 
      url : 'inc/ajax.php', 
      type : 'POST', 
      data : { 
       action : 'unlike_post', 
       poid : $(self).data('poid') 
      }, 
      dataType : 'JSON', 
      success : function(result) { 
       if (result.xhr == 'success') { 
        $(self).attr('disabled','true'); 
        $($(self).parent()).find('.likes').html(parseInt($($(self).parent()).find('.likes').html()) - 1); 
       } else if (result.xhr == 'error'){ 
        alert('An internal error occured, try again later.') 
       } 
      } 
     }); 
    }); 
}); 

것이 있는지 확인하는 클래스 likes, unlikebuttonlikebutton이 추가됩니다. 그리고 부모를 추가했는지 확인하십시오. Live Demo.

HTML 변경

<div class='media-body'> 
    <h4 class='media-heading'>post #1</h4> 
    <p>post #1</p> 
    <button data-poid="10" class="btn btn-link btn-xs likebutton" style="font-size: 14px;"><i class="fa fa-thumbs-up"></i> <small>Like</small> 
    </button> 
    <h5 class='likes' style="display: inline;">0</h5> <small>likes</small> 
    <small style="cursor:pointer;" onClick="$('#comments10').toggle('slow');">Add Comment</small> 
    <form action="" method="post" id="comments10" style="display:none;"> 
     <input type="hidden" name="id" value="10"> 
     <textarea style="width:100%;height:100px;" name="comment"></textarea> 
     <br /> 
     <input type="submit" class="btn btn-primary" value="Add comment" /> 
    </form> 
</div> 
+0

이 코드를 붙여 넣고 모든 것을 수업으로 변경했습니다.하지만 좋아요 또는 다른 버튼을 클릭하면 아무 일도 일어나지 않습니다. –

+0

@JordanJones, 데이터에서 클래스로 ID를 변경하는 것을 잊었습니다. 다시 시도해 볼까요? –

+0

나는 그것을 벌써했다, 아직도 아무것도하지 않았다. 방화범은 아무 말도하지 않습니다. –

관련 문제