带有链接未选中复选框的 HTML 表格行

HTML Table row with link not checking checkbox

本文关键字:HTML 表格 复选框 链接      更新时间:2023-09-26

我有一个在PHP中回显的HTML表:

echo '<tr class="notfirst" style="cursor:pointer;" onclick="document.location=''editinvoice.php?seq='.$result["sequence"].'&inv='.$result["invoice_number"].'''">
                <td width="20"><input type="checkbox" name="check'.$counter.'" id="check'.$counter.'" onclick=''add('.$total.', this);'' /></td>
                <td width="150">'.$result["invoice_number"].'</td>
                <td width="250">'.$company.'</td>
                <td width="100">'.$date.'</td>
                <td width="100">&pound;'.$result["total"].'</td>
                <td width="100">&pound;'.$result["total"].'</td>
            </tr>';

因此,当您将鼠标悬停在它上面时,它会突出显示整行,无论您单击该行的哪个位置,它都会打开链接,但是当我选中复选框时,它也会打开链接 - 我想停止此操作

我认为最好

将javascript代码与html标记分开。这样你就可以更好地控制它。

看看 javascript 中的冒泡阶段,看看 preventdefault我希望这有帮助

我会使用event.stopPropagation()

这是一个jQuery版本,因为它更容易做到,但如果必须,你可以在DOM访问中重写它。如果这样做,还需要为 IE<9 添加event.cancelBubble=true

$(function() {
  $(".notfirst").on("click",function() {
    location = "editinvoice.php?seq="+$(this).data("seq")+"&inv="+$(this).data("inv");
  });
  $("checkbox[name^=check]).on("click",function(event) {
    event.stopPropagation();
    add($(this).data("total");
  });
});

使用此代码:

echo '<tr class="notfirst" style="cursor:pointer;" data-seq="'.$result["sequence"].'" data-inv="'.$result["invoice_number"].'">
  <td width="20"><input type="checkbox" name="check'.$counter.'" id="check'.$counter.'" data-total="'.$total.'" /></td>
            <td width="150">'.$result["invoice_number"].'</td>
            <td width="250">'.$company.'</td>
            <td width="100">'.$date.'</td>
            <td width="100">&pound;'.$result["total"].'</td>
            <td width="100">&pound;'.$result["total"].'</td>
        </tr>';