仅针对外部div的fire mouseup事件

时间:2017-10-03 18:32:09

标签: javascript html dojo

我在另一系列div中有一个HTML元素(表单元素 - 文本框)。 我在外部div上创建了mouseup事件的监听器,但是当我点击文本框时会触发它。

我认为只有当我将侦听器附加到该元素时才会触发外部div上的mouseup - 而不是文本框

当'mouseup'在文本框中触发时,有没有办法防止它被触发?

require([
    "dijit/form/TextBox",
    "dojo/on",
    "dojo/dom"
], function (
TextBox,
on,
dom) {
    var box = new TextBox({
        name: "any",
        value: "",
        placeholder: "Type anything here"
    }, "textBox");
    
    var canvas = dom.byId("outerDiv");
    on(canvas, "mouseup", function (e) {
    alert();
    });
});
dojo.require("dijit.form.anyText");
 var textBox = dijit.byId("textBox");
   console.log( "--- >> "+textBox.get("value"));
   
   
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<Div id="outerDiv" style="width: 3in; height: 3in; border: 1px solid;border-color:black; cursor: pointer;">
  <Div id="innerDiv" style="height: auto; border: 1px solid;border-color:blue;">
    <div  id="textBox" readonly></div>
  </Div>
</Div>

2 个答案:

答案 0 :(得分:1)

单击文本框时,事件"bubbles up"到外部元素。

JavaScript&#39; Event.stopPropagation()&#34;阻止当前事件在捕获和冒泡阶段进一步传播&#34;。

以下是纯JavaScript中的示例,但另请参阅dojo.stopEvent

&#13;
&#13;
var outerDiv = document.getElementById('outerDiv');
var textBox = document.getElementById('textBox');

outerDiv.addEventListener('mouseup', function(event) {
  console.log('mouse up on outer div');
});
textBox.addEventListener('mouseup', function(event) {
  event.stopPropagation();
  console.log('mouse up on text box');
});
&#13;
#outerDiv {
  width: 3in;
  height: 3in;
  border: 1px solid;
  border-color: black;
  cursor: pointer;
}

#innerDiv {
  height: auto;
  border: 1px solid;
  border-color: blue;
}
&#13;
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<Div id="outerDiv">
  <Div id="innerDiv">
    <div id="textBox" readonly>textbox</div>
  </Div>
</Div>
&#13;
&#13;
&#13;

修改

这是一个Dojo示例:

&#13;
&#13;
require([
  "dijit/form/TextBox",
  "dojo/on",
  "dojo/dom"
], function(
  TextBox,
  on,
  dom) {

  var box = new TextBox({
    name: "any",
    value: "",
    placeholder: "Type anything here"
  }, "textBox");

  var canvas = dom.byId("outerDiv");

  on(box, "mouseup", function(e) {
    console.log('mouse up on text box');
    dojo.stopEvent(e);
  });

  on(canvas, "mouseup", function(e) {
    console.log('mouse up on outer div');
  });

});
&#13;
#outerDiv {
  width: 3in;
  height: 3in;
  border: 1px solid;
  border-color: black;
  cursor: pointer;
}

#innerDiv {
  height: auto;
  border: 1px solid;
  border-color: blue;
}
&#13;
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>

<Div id="outerDiv">
  <Div id="innerDiv">
    <div id="textBox" readonly>textbox</div>
  </Div>
</Div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在创建提醒之前检查ID

on(canvas, "mouseup", function (e) {
    if (e.target.id == "outerDiv") {
       alert();
    }
});

JS Fiddle