2012-11-04 2 views
0

replaceWith()select()을 할당 할 수 있습니까?replaceWith 및 textarea 선택

$('#foo').one('click', function() { 
$(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>'); 
}); 

$('#copy').click(function() { 
$(this).select(); 
}); 

나는 위의 코드를 해봤지만 작동 나던 (난 당신이 내가) 무슨 뜻인지 얻을 경우 replaceWith()는 가상의 요소 (때문에이 가정).

나는 그러나 replaceWith()

$('#foo').one('click', function() { 
$(this).replaceWith('<textarea id="copy" onclick="this.focus();this.select()">'+$(this).text()+'</textarea>'); 
}); 

내부 onclick="this.focus();this.select()"를 배치하여 작업을 가지고 있지만, 첫 번째 코드가 시도되는 것처럼 replaceWith() 코드의 외부를 선호하는 것이다.

답변

1

원본 코드에서 클릭 이벤트를 존재하지 않는 개체 (바인딩 시점에는 존재하지 않음)에 바인딩합니다.

다음은이 텍스트 필드를 DOM에 삽입 한 후 클릭 이벤트 을 바인드하여 작동해야합니다.

$('#foo').one('click', function() { 
    $(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>'); 

    // at this point, the textarea exists and the binding will work. 
    $('#copy').click(function() { 
    $(this).select(); 
    }); 
}); 

또 다른 방법은 문서 객체에 #copy의 모든 클릭에 대해()에 사용하여 바인딩됩니다.

$('#foo').one('click', function() { 
    $(this).replaceWith('<textarea id="copy">'+$(this).text()+'</textarea>'); 
}); 

// in this case, it will work even if #copy is non-existant at the time of binding 
$(document).on('click', '#copy', function() { 
    $(this).select(); 
}); 
+0

나는 그것이 내가 "가상의 요소는"너무 간단하게 들으 일을해야 #foo 클릭으로 선택 코드를 이동, 올바른 용어를 몰랐 의미 무엇으로 오브젝트가 존재하지 않는 것을 깨달았다 :) –