2012-07-01 4 views
0

값으로 html 요소를 찾고 싶습니다. 나는 ID로했지만, 내 경우는 깨지기 쉬운 :값으로 html 요소를 찾는 방법

의사 코드 :

for user in users: 
<li id="followed" onclick="follow($(this).text())"><a class="follow">user.name</a></li> 
endfor 

내가 각 사용자 이름을 클릭 할 수 있음을 원하고 내가 DB로 그를 저장하고에 "저장"추가 해요 사용자 이름의 끝 부분. like :

"username" ==> after click: "username saved" 

저는 이것을 ajax를 통해합니다.

function follow(data){ 
    var Him = data; 
    alert(Him); 
    $.ajax({ 
     url: "/follow", 
     type: "POST", 
     datatype: "html", 
     data: {Him: Him} 
    }).success(function(response){ 
     $('#followed').append(response); 
    }); 
} 

이 코드는 괜찮지 만, 루프의 말에, 모든 사용자 이름이 id='followed'을 가지고 있기 때문에, 첫 번째 이름에 "저장"응답을 추가한다.

그래서 HTML 요소를 그 값으로 찾고 싶습니다. 예 : "사용자 이름".
가능합니까?

+1

'$ ('[값 = "foo에"]') ' – elclanrs

+1

모두'. 'follows '의 값으로 1 개 이상의'id'를 갖는 것은 유효하지 않은 HTML이고 부작용이 있습니다. 예를 들어, jQuery는 모두 대신 첫 번째를 선택하는 것뿐입니다. 요소에 jQuery'$ (selector) .data'를 사용하는 상태를 나타내려면 Darin의 대답에서 볼 수 있듯이 사용자 정의 속성'$ (selector) .attr ("myState", "following")'또는 클래스를 추가하십시오 . – Nope

+0

네, 당신은 완전히 맞습니다. 나는 제대로주의를 기울이지 않았습니다. 감사합니다. – doniyor

답변

4

context 매개 변수를 사용하여 AJAX 요청의 성공 콜백에 전달 된 컨텍스트를 변경할 수 있습니다.

그러나 먼저이 루프 인 경우의 당신의 마크 업을 청소 대신 ID의 클래스 이름을 사용하여 시작하자 당신이 ID를 HTML에서 고유해야합니다 알고 있기 때문에 우리가 청소 한 것을 지금,

for user in users: 
    <li class="followed"><a class="follow">user.name</a></li> 
endfor 

좋아 마크 업까지의이 <li>.click() 이벤트에 겸손하게 가입하자 고유해야합니다 페이지에 속성 id`

$(function() { 
    $('.followed').click(function() { 
     // Remark: maybe you wanna get just the username inside the anchor in which case 
     // you probably need "var Him = $('a', this).text();" 
     var him = $(this).text(); 
     $.ajax({ 
      url: '/follow', 
      type: 'POST', 
      dataType: 'html', 
      context: this, // <!-- Here, that's the important bit 
      data: { him: him }, 
     }).success(function(response) { 
      // since we have used the context, here 'this' will no 
      // longer refer to the XHR object (which is the default) but 
      // to whatever we have passed as context (in our case this 
      // happens to be the <li> that was clicked) => we can be certain 
      // that we are updating the proper DOM element 
      $(this).append(response); 
     }); 
    }); 
}); 
+1

분당 150 단어를 입력 하시겠습니까? –

+0

@ Darin - 내가 얻은 최고의 대답 !!! 감사의 톤! – doniyor

+0

@ Jared. : 빠른 D 조 예! – doniyor

관련 문제