「ライブ」機能を使用して、テーブルの行でクリック操作を行います。
$("tr").live('click',function() {
alert('Some table row is clicked');
});
どの行がクリックされ、どの行が使用されているかを調べ、それif-elseに基づいてカスタム アラートを生成したいと考えています。誰かがそれを行う方法を教えてもらえますか?
どうもありがとう。
編集1:
クリックした行の要素を関数内で参照する方法はありますか?
「ライブ」機能を使用して、テーブルの行でクリック操作を行います。
$("tr").live('click',function() {
alert('Some table row is clicked');
});
どの行がクリックされ、どの行が使用されているかを調べ、それif-elseに基づいてカスタム アラートを生成したいと考えています。誰かがそれを行う方法を教えてもらえますか?
どうもありがとう。
編集1:
クリックした行の要素を関数内で参照する方法はありますか?
$("tr").live('click', function() {
if (this.id == "foo") {
alert('the tr with the foo id was clicked');
}
});
行番号を確認したい場合は、次を使用しますindex。
$("tr").live('click', function() {
if $(this).index() === 2) {
alert('The third row was clicked'); // Yes the third as it's zero base index
}
});
アップデート:
$("tr").live('click', function() {
// "this" is the clicked <tr> element
// $(this).find('td span') is the spans inside a td inside the clicked <tr>
}
まず、 .live() を使用しないでください:)
代わりに使用できます .delegate()
例
$(document).delegate("tr", "click", function(e) {
// write your code here
});
簡単な方法を提案しましょう。これがあなたのテーブルであるとします:
<table>
<tr id = '1' class="tr">...</tr>
<tr id = '2' class="tr">...</tr>
<tr id = '3' class="tr">...</tr>
</table>
これを jQuery コードに配置します。
$(function(){
$('.tr').click(function(){
var row_no = $(this).attr('id');
alert('Row number '+row_no+' was clicked');
});
});
これがお役に立てば幸いです。
デモ: http://jsfiddle.net/zJUuX/
HTML :
<table>
<tr><td>hey</td></tr>
<tr><td>hi</td></tr>
</table>
Jクエリ:
$("table tr").click(function(){
messages( $(this).index() );
});
function messages(index) {
switch(index){
case 0:
alert("you clicked 1st row");
break;
case 1:
alert("you clicked 2nd row");
break;
default:
break;
}
$("table tr").eq(index).css("background","#ff0");
$("table tr").eq(index).find("a"); //will find all the nested anchor tags.
}
学習者の皆さん、これで仮想ポイントを受け入れます :D. 楽しむ。
を使用して、クリックした要素にアクセスできますthis。
offtopic : $.live は 1.7 以降非推奨です。$.on を使用する必要があります。詳細については、こちらを参照してください。
gdoron の回答の改善として、jQuery の live() は非推奨になっているため、delegateまたはon:
$("#mytable").delegate("tr", "click", function(e) {
if (this == "foo") {
....
}
});
//Even row
$("tr:even").click(function() {
alert('Even');
});
//Odd row
$("tr:odd").click(function() {
alert('Odd');
});