2016-01-23 303 views
2

我想觸發一個表格單元格的數據變化事件。onchange td表的事件?

//表生成代碼

<table id=custorder2 > <head> <tr> <td>change it</td> </tr> </head> <tbody> <tr> <td>1</td> </tr> </tbody> </table> 

//用於觸發事件是這樣的

$(document).ready(function(){ 
    $('#custorder2 tr td').change(function() { 
     console.log("call"); 
    }) 
}) 

對細胞值的變化應打印此通話。

+0

TD不是輸入元素,其值可以改變嗎?你的意思是'編程改變'嗎? – gurvinder372

+0

是的,你得到它的權利 – RishiPandey

+0

onChange不適用於td或tr – Raviteja

回答

1

您可以嘗試使用類似DOMSubtreeModified,DOMNodeInserted,DOMNodeRemoved或它們的組合的事件。

$('#custorder2 tr td').on("DOMSubtreeModified", function(){ 
 
    alert('changed'); 
 
}); 
 
$('button').on('click', function(){ 
 
    $('#custorder2 tr td').text(this.id); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id=custorder2 > <head> <tr> <td>change it</td> </tr> </head> <tbody> <tr> <td>1</td> </tr> </tbody> </table> 
 
<button id="id1">Change 1</button> 
 
<button id="id1">Change2</button>

+0

這不適合我,但是使用'$(「#custorder2」).bind(「DOMSubtreeModified」,function(){})'類似的[answer](https://stackoverflow.com/a/28044851/3976696)'做了。 – sc28

2

如果你正在考慮標準的編輯細胞,然後我想提出一個替代方案,

<script language="javascript"> 
function dotest(element,event) 
{ 
    //GET THE CONTENT as TEXT ONLY, you may use innerHTML as required 
    alert("content " + element.textContent) 

} 
</script> 
<table cellpadding="2" cellspacing="0" border="1" width="100%"> 
    <tr> 
<td contenteditable="true" onkeyup="javascript:dotest(this,event);"> 

    Testing 
</td> 
</tr> 
</table> 

憑藉HTML5的屬性和按鍵(在場景中的細胞能直接編輯)

希望你覺得它有用

-1

順便提一下,on-change事件在tr或td上不起作用,但如果你想嘗試,你可以通過下面的代碼。

在你的代碼,我想這目標沒有被認可,所以嘗試做:

$("#custorder > tr > td").change(function(){ 
}); 

相反( 「#custorder TR TD」)的改變(函數(){});

HTML:

<table id=custorder2 > 
<head> 
    <tr> 
     <td>change it</td> 
    </tr> 
</head>   
<tbody> 
    <tr> 
     <td>1</td> 
    </tr> 
</tbody> 
</table> 

的Javascript:

$("#custorder > tr > td").change(function() { 
    console.log("inside change event"); 
}); 
+0

如果表是動態創建的,它會起作用。 – RishiPandey

+0

我在我的代碼中使用了這種方法它不起作用 – RishiPandey

+0

即使您的表是動態創建的,那麼我也不認爲它會起作用。 –