j클릭시 이벤트를 동적으로 추가된 HTML 요소에 바인딩하는 방법 쿼리
클릭 시 이벤트를 jQuery를 사용하여 동적으로 삽입하는 요소에 바인딩합니다.
그러나 바인딩된 기능은 실행하지 않습니다.이 예제가 작동하지 않는 이유와 제대로 작동하는 방법을 알려주시면 감사하겠습니다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
<title>test of click binding</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
jQuery(function(){
close_link = $('<a class="" href="#">Click here to see an alert</a>');
close_link.bind("click", function(){
alert('hello from binded function call');
//do stuff here...
});
$('.add_to_this').append(close_link);
});
</script>
</head>
<body>
<h1 >Test of click binding</h1>
<p>problem: to bind a click event to an element I append via JQuery.</p>
<div class="add_to_this">
<p>The link is created, then added here below:</p>
</div>
<div class="add_to_this">
<p>Another is added here below:</p>
</div>
</body>
</html>
EDIT: 메소드가 삽입되는 두 가지 요소를 포함하도록 예제를 편집했습니다.그런 경우에는.alert()콜은 실행되지 않습니다 ( @(댓글로 지적해주신 @Daff 감사합니다)
이 방법은 모두 사용하지 않습니다.를 사용해야 합니다.on당신의 문제를 해결하는 방법.
동적으로 추가되는 요소를 대상으로 하려면
$(document).on('click', selector-to-your-element , function() {
//code here ....
});
상각된 합니다를 합니다..live()방법.
첫 번째 문제는 둘 이상의 요소가 있는 jQuery 집합에서 append를 호출하면 각각에 대해 append할 요소의 클론이 생성되고 따라서 연결된 이벤트 관찰자가 손실된다는 것입니다.
이를 위한 대안적인 방법은 각 요소에 대한 링크를 만드는 것입니다.
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
또 다른 잠재적인 문제는 요소가 DOM에 추가되기 전에 이벤트 관찰자가 부착되어 있다는 점일 수 있습니다.이것이 무슨 할 말이 있는지는 모르겠지만, 그 행동은 결정되지 않은 것으로 여겨질 수도 있다고 생각합니다.보다 확실한 접근 방식은 다음과 같습니다.
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
라이브 방법은 어떻습니까?
$('.add_to_this a').live('click', function() {
alert('hello from binded function call');
});
그래도 당신이 한 일은 효과가 있을 것 같군요.비슷한 글이 하나 더 있네요.
파티에 조금 늦었지만 jQuery 이벤트 핸들러의 일반적인 오해를 해소하려고 했습니다. jQuery 1.7준 ,.on() 상각된다 해야 합니다..live()된 후 합니다.
해서 , 를 이 아닙니다.live위해서on구문이 약간 다르기 때문입니다.
새로운 방법(예 1):
$(document).on('click', '#someting', function(){
});
사용하지 않는 방법(예 2):
$('#something').live(function(){
});
위와 같이 차이가 있습니다.은입니다..on()다와 수 ..live()jQuery 으로써 를:
예 3:
$('#something').on('click', function(){
});
단, 사용하지 않고는$(document)예제 1과 같이 예제 3은 동적으로 생성된 요소에 대해 작동하지 않습니다.동적 위임이 필요하지 않다면 예제 3은 절대적으로 좋습니다.
$(document.on()을 모든 것에 사용해야 합니까?
효과는 있겠지만 동적 위임이 필요 없는 경우 브라우저에서 예제 1을 작업해야 하므로 예제 3을 사용하는 것이 더 적합할 것입니다.성능에 실질적인 영향을 미치지는 않겠지만 사용에 가장 적합한 방법을 사용하는 것이 타당합니다.
동적 위임이 필요 없는 경우 .click() 대신 .on()을 사용해야 합니까?
꼭 그렇다고 할 수는 없죠.다음은 예 3과 같은 바로 가기입니다.
$('#something').click(function(){
});
위의 내용은 완벽하게 유효하며, 따라서 동적 위임이 필요 없는 경우 어떤 방법을 사용하는지는 개인의 선호도의 문제입니다.
참조:
예를 들어 다음과 같습니다.
jQuery(function(){
var close_link = $('<a class="" href="#">Click here to see an alert</a>');
$('.add_to_this').append(close_link);
$('.add_to_this').children().each(function()
{
$(this).click(function() {
alert('hello from binded function call');
//do stuff here...
});
});
});
모든 특정 요소에 부착하기 때문에 효과가 있을 것입니다.이것이 DOM에 링크를 추가한 후 추가된 요소를 DOM의 JQuery 요소로 명시적으로 선택하고 클릭 이벤트를 DOM에 바인딩하는 방법을 찾아야 하는 이유입니다.
가장 좋은 방법은 아마도 라이브 방법을 통해 특정 클래스에 바인딩하는 것일 것입니다.
요소와 함께 클릭 이벤트를 생성할 수도 있고 필요한 경우도 있습니다.예를 들어 선택기 기반 바인딩이 옵션이 아닌 경우에 해당됩니다.핵심적인 부분은 토바이어스가 이야기하던 문제를 해결하기 위해서입니다..replaceWith()단일 원소로이것은 단지 개념의 증명일 뿐입니다.
<script>
// This simulates the object to handle
var staticObj = [
{ ID: '1', Name: 'Foo' },
{ ID: '2', Name: 'Foo' },
{ ID: '3', Name: 'Foo' }
];
staticObj[1].children = [
{ ID: 'a', Name: 'Bar' },
{ ID: 'b', Name: 'Bar' },
{ ID: 'c', Name: 'Bar' }
];
staticObj[1].children[1].children = [
{ ID: 'x', Name: 'Baz' },
{ ID: 'y', Name: 'Baz' }
];
// This is the object-to-html-element function handler with recursion
var handleItem = function( item ) {
var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");
if(typeof item.children !== 'undefined') {
ul = $("<ul />");
for (var i = 0; i < item.children.length; i++) {
ul.append(handleItem(item.children[i]));
}
li.append(ul);
}
// This click handler actually does work
li.click(function(e) {
alert(item.Name);
e.stopPropagation();
});
return li;
};
// Wait for the dom instead of an ajax call or whatever
$(function() {
var ul = $("<ul />");
for (var i = 0; i < staticObj.length; i++) {
ul.append(handleItem(staticObj[i]));
}
// Here; this works.
$('#something').replaceWith(ul);
});
</script>
<div id="something">Magical ponies ♥</div>
function load_tpl(selected=""){
$("#load_tpl").empty();
for(x in ds_tpl){
$("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
}
$.each($("#load_tpl a"),function(){
$(this).on("click",function(e){
alert(e.target.id);
});
});
}
저는 그것이 좋은 방법이라고 믿습니다.
$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '.close', function(){
var rowid='row'+this.id;
var sl = '#tblData tr[id='+rowid+']';
console.log(sl);
$(sl).remove();
});
$("#addrow").click(function(){
var row='';
for(var i=0;i<10;i++){
row=i;
row='<tr id=row'+i+'>'
+ '<td>'+i+'</td>'
+ '<td>ID'+i+'</td>'
+ '<td>NAME'+i+'</td>'
+ '<td><input class=close type=button id='+i+' value=X></td>'
+'</tr>';
console.log(row);
$('#tblData tr:last').after(row);
}
});
});
</script>
</head>
<body>
<br/><input type="button" id="addrow" value="Create Table"/>
<table id="tblData" border="1" width="40%">
<thead>
<tr>
<th>Sr</th>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
</table>
</body>
</html>
언급URL : https://stackoverflow.com/questions/1525664/jquery-how-to-bind-onclick-event-to-dynamically-added-html-element
'programing' 카테고리의 다른 글
| MySQL에서 128비트 숫자를 한 열에 저장하는 방법? (0) | 2023.09.21 |
|---|---|
| gcc로 C를 컴파일할 때 전처리된 .i 파일에서 숫자의 의미는 무엇입니까? (0) | 2023.09.21 |
| 깃 푸시가 "빠른 방향으로 이동하지 않음"을 거부했습니다. (0) | 2023.09.21 |
| 초기 데이터 로드(angularjs) (0) | 2023.09.21 |
| 지시문에서 호스트 구성 요소에 액세스하는 방법은 무엇입니까? (0) | 2023.09.21 |