2016-03-21 64 views
0

標籤的類名創建由jQuery的一些標籤,並定義一個類名狀波紋管:在其他地方,我想訪問jQuery中

$('#tr').html('<select class="optcode"> 
       <option>select code</option> 
       <option>select code</option>' 
       </select>); 

過訪問<select>類名的代碼波紋管,但它不起作用我該如何解決這個問題:

$('.optcode').change(function(){ 
    alert('something'); 
}) 

回答

0

嘗試使用delegate: -

$('#tr').on('change', '.optcode', function(){ 
    alert('something'); 
}); 
+0

謝謝你有用 –

0

更改函數沒有綁定到元素,因爲它們在代碼執行時不存在於DOM中。您可以使用函數將元素同時添加到DOM和綁定。

像這樣的工作:

function doStuff() { 

    $('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>'); 

    $('.optcode').change(function(){ 
     alert('something'); 
    }) 

} 

$(document).ready(function() { 
    doStuff(); 

}) 

你可以看到它在這方面的工作JS小提琴:https://jsfiddle.net/hsvnhhn7/

希望有所幫助。

0

只是改變

$('#tr').html('<select class="optcode"> 
       <option>select code</option> 
       <option>select code</option>' 
       </select>); 

TO

$('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>'); 

看到演示

$('#tr').html('<select class="optcode"><option>select code</option><option>select code</option></select>'); 
 

 
$('.optcode').change(function(){ 
 
    alert('something'); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="tr"></div>