【问题标题】:Check the form element triggered at onclick event检查 onclick 事件触发的表单元素
【发布时间】:2014-11-01 01:24:18
【问题描述】:

我在网页中有一个 js 函数,可以捕获点击的位置。如果页面包含表单元素,我必须以一种可以识别的方式来实现它,如果是这样,请检查我正在记录的点击是否是在随机表单元素上进行的。 我起身检查表单并了解其元素,但我不知道如何检查单击是否针对单个元素:

$('*').on('mousedown', function (e) {
 // make sure the event isn't bubbling
 if (e.target != this) {
    return;
 }
 // do something with the click somewhere
 // for example, get the coordinates:
 x = e.pageX;
 y = e.pageY;
 pa = $(location).attr('href');
 //Window dimension
 var width = $(window).width();
 //var width = $getWidth();
 var height = $(window).height();

 //Check if page contain a form
 var elementF =  document.querySelectorAll('form');
 var fname = '';
 var elements = '';
 for (var i=0; i<elementF.length; i++){
  fname = elementF[i].id;
  elements = document.forms[fname].elements;
  for (x=0; x<elements.length; x++){
    //Now i need to check if element is clicked or not
  }
}

【问题讨论】:

  • 哇...你可能只是说你想使用一个ID?你会给你的表单一个 id 属性,然后使用document.getElementById(id_here)
  • 我已经知道表单是否存在,并且我已经知道其元素的所有 id,我需要知道我正在记录的点击是否在这些项目之一上完成

标签: javascript jquery forms dom


【解决方案1】:

您在这里所做的是将 mousedown 事件绑定到页面上的每个元素。这将是资源密集型的,并且不是必需的。此外,由于它无处不在,if (e.target !== this){ return; } 确实可以防止它在鼠标按下某物时触发一百万次,而且还可以防止它冒泡。让它冒泡并使用e.targete.currentTarget 来区分。不应该有任何理由这样做$('*').on("mousedown")

你为什么不能这样做?

$("form").on("click", function(e){
    // e.currentTarget will be the form element capturing the click

    console.log( $(e.currentTarget).html() );

    // e.target will be whatever element you clicked on
    // so you can do whatever you want with it

    console.log( $(e.target).text() );

    // All your handler code here
});

一些可能有用的东西

【讨论】:

    【解决方案2】:

    试试

    $('*').on('mousedown', function (e) {
      var elementClicked = e.target.nodeName;
      console.log("element: " + elementClicked)
    })
    

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 2022-08-03
      • 2017-04-12
      • 1970-01-01
      • 2010-11-02
      • 2013-12-28
      • 2021-05-14
      • 2012-12-19
      • 2011-08-29
      相关资源
      最近更新 更多