2016-06-16 2 views
0

「マイボタン」を使用するための正しいセレクタは何ですか? 私はこのサイトを検索しましたが、私のために働くことはありませんか?Jquery Right要素/ボタンで使用するセレクタ.html()を使用して動的にロードされていますか?

<!DOCTYPE HTML> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="robots" content="index, all" /> 
<title>Example</title> 
</head> 

<body> 
    <div id="result"><!--results--> 
    </div> 
<!-- jQuery --> 
<script src="js/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     //generate table 
     htmlx='<table class="table table-condensed">'; 
     htmlx+='<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>'; 
     htmlx+='</table>'; 
     $('#result').html(htmlx);    
    }); 

    $("#bt_kgt2").on("click", function() { 
     alert ("button clicked!"); 
    }); 
</script> 
</body> 
</html> 

答えて

1

要素が追加される前に、クリックイベントハンドラをバインドしようとしています。 DOMに要素を追加した後にバインドするか、またはクリックイベントハンドラをバインドする2つのオプションがあります。

$(document).ready(function() { 
 
    //generate table 
 
    htmlx = '<table class="table table-condensed">'; 
 
    htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>'; 
 
    htmlx += '</table>'; 
 
    $('#result').html(htmlx); 
 
    $("#bt_kgt2").on("click", function() { 
 
    alert("button clicked!"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"> 
 
    <!--results--> 
 
</div>


それとも私のために動的に追加された要素

$(document).ready(function() { 
 
    //generate table 
 
    htmlx = '<table class="table table-condensed">'; 
 
    htmlx += '<tr><td align="center"><button type="button" id="bt_kgt2" name="bt_kgt" class="btn btn-info">My Button</button></td></tr>'; 
 
    htmlx += '</table>'; 
 
    $('#result').html(htmlx); 
 

 
}); 
 

 
$('#result').on("click", "#bt_kgt2", function() { 
 
    alert("button clicked!"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"> 
 
    <!--results--> 
 
</div>

+0

仕事の両方が助けを..thanks聞くためにevent delegationを使用 –

+0

@ランズマン:喜んで:) –

関連する問題