jquery 从div内的内容以及div本身触发JavaScript

niwlg2el  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(187)

我有一个携带数据属性的div。在div本身上长按(data-long-press-delay)时,会触发一个JavaScript函数。但是,div包含一个<table>,它占据了整个div。因此,在div周围有最小的区域,实际上是可点击的,以便触发JavaScript函数。
我怎样才能使表也能触发JavaScript函数,因为它存储在div中,因此应该触发函数?
我尝试将数据属性添加到表中,但这并没有触发JavaScript函数。

document.addEventListener('long-press', assign);

function assign(e) {
  var reg = $(e.target).attr("data-reg");
  var fnum = $(e.target).attr("data-fnum");
  var route = $(e.target).attr("data-route");

  if (reg == null) {
    throw new Error("Something went badly wrong!");
  } else {
    input = window.prompt("Enter input " + reg + " / " + fnum, "");
  }

  if (input) {
    // do something
  }
};

/*!
 * long-press.js
 * Pure JavaScript long-press event
 * https://github.com/john-doherty/long-press
 * @author John Doherty <www.johndoherty.info>
 * @license MIT
 */
! function(t, e) {
  "use strict";

  function n() {
    this.dispatchEvent(new CustomEvent("long-press", {
      bubbles: !0,
      cancelable: !0
    })), clearTimeout(o), console && console.log && console.log("long-press fired on " + this.outerHTML)
  }
  var o = null,
    u = "ontouchstart" in t || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0,
    s = u ? "touchstart" : "mousedown",
    i = u ? "touchcancel" : "mouseout",
    a = u ? "touchend" : "mouseup",
    c = u ? "touchmove" : "mousemove";
  "initCustomEvent" in e.createEvent("CustomEvent") && (t.CustomEvent = function(t, n) {
    n = n || {
      bubbles: !1,
      cancelable: !1,
      detail: void 0
    };
    var o = e.createEvent("CustomEvent");
    return o.initCustomEvent(t, n.bubbles, n.cancelable, n.detail), o
  }, t.CustomEvent.prototype = t.Event.prototype), e.addEventListener(s, function(t) {
    var e = t.target,
      u = parseInt(e.getAttribute("data-long-press-delay") || "1500", 10);
    o = setTimeout(n.bind(e), u)
  }), e.addEventListener(a, function(t) {
    clearTimeout(o)
  }), e.addEventListener(i, function(t) {
    clearTimeout(o)
  }), e.addEventListener(c, function(t) {
    clearTimeout(o)
  })
}(this, document);
td {
  height: 80%;
  width: 80%;
  border: 1px solid black;
  background-color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 100px; width: 100px; background: black;" data-route="route" data-reg="reg" data-fnum="fnum" data-long-press-delay="100">

  <table>
    <tbody>
      <tr>
        <td>Long press here</td>
      </tr>
    </tbody>
  </table>
</div>

相关问题