5

各テーブルの行を (リンクとして) クリック可能にするスクリプトがありますが、この列を「編集」ボタンとしてそのままにしておく必要があります。機能するようにスクリプトを修正するのを手伝ってくれる人はいますか?

これまでのjQueryは次のとおりです。

$(document).ready(function() {
  $('#movies tr').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});

1 行の HTML は次のとおりです。

<table id="movies">
  <tr class='odd'>
    <td>1</td>
    <td><a href='/film.php?id=1'></a>Tintin</td>
    <td>Tintin and Captain Haddock set off on a treasure hunt for a sunken ship.</td>
    <td><a href='/edit.php?id=1'>edit</a></td>
  </tr>
  .....
4

6 に答える 6

11

さらに一歩進んでtrの要素を制御し、tdの最後ではないそれぞれにクリック ハンドラをバインドする必要がありtrます。

$(document).ready(function()
{
   $('#movies tr').each(function(i,e)
   {
      $(e).children('td:not(:last)').click(function()
      {
         //here we are working on a td element, that's why we need
         //to refer to its parent (tr) in order to find the <a> element
         var href = $(this).closest("tr").find("a").attr("href");
         if(href)
         {
            window.location = href;
         }              
      });
   });
});
于 2011-11-05T11:17:16.720 に答える
3

event.stopImmediatePropagation()または、最後の列ボタン イベント ハンドラーで使用することもできます。

$('#movies tr').click(function () {
    var href = $(this).find("a").attr("href");
    if(href) window.location = href;
});

$('#movies input:button').click(function (e) {
    // button's stuff
    e.stopImmediatePropagation();
});

利点(または不便)は、最後のセルのボタンをクリックできることです。(マージンパディング内)。ボタンをクリックしないと、リンク先のページが開いてユーザーを驚かせてしまうので、不便です。

もう 1 つの方法は、event.which で実行するアクションを決定するイベント ハンドラーを 1 つだけ使用することです。イベント ハンドラーの数を制限するので、これは私のお気に入りの方法です。デリゲートの使用も同じ理由です。行ごとではなく、テーブルごとに 1 つのハンドラー。

$('#movies').delegate('tr', 'click', function (e) {
    if ( $(e.target).is('input:button') )  {
        // button's stuff
    }
    else {
        var href = $(this).find("a").attr("href");
        if(href) window.location = href;
    }
});
于 2011-11-05T12:46:56.943 に答える
0

代わりに<td>、特定のクラスまたは類似の s を 0 にパディングし、<a>内部にタグを配置して、ブラウザーが全体の -tag をdisplay: blockクリックするだけにすることをお勧めします。<a><td>

ここでの利点は、ブラウザがリンクをより適切に処理できることです。たとえば、必要に応じてリンクを新しいウィンドウで開くことができます。

ここでのソリューションには適さないかもしれませんが、同様のケースについて検討する価値があります。

于 2011-11-05T12:28:01.667 に答える
0
$('tr').each(function () {
    $(this).children('td:not(:first)').click(function () {
        window.location = $(this).closest('tr').data('href');
        return false;
    });
});
于 2014-02-03T23:11:53.703 に答える
0

これを試して

$(document).ready(function() {
  $('#movies tr:not('.odd')').click(function() {
    var href = $(this).find("a").attr("href");
    if(href) {
      window.location = href;
    }
  });
});
于 2011-11-05T11:26:25.637 に答える