我正在做一个非常简单的Jquery驱动的事件,用户点击两个div元素,然后用所选项目的数据进行API调用。由于某种原因,$.post函数触发了我的$(".objects").click()调用,将窗口设置为这样。一开始我以为它会导致双击(因为click函数依赖于元素中的数据,而window没有),直到我做了一些调试。下面是我的代码:
HTML:
<div class="option-selection" data-value="1">Option 1</div>
<div class="option-selection" data-value="2">Option 2</div>
<div class="option-selection" data-value="3">Option 3</div>
<div class="option-selection" data-value="4">Option 4</div>
... etc ...Javascript:
$(".option-selection").click(function(ev) {
console.log("CLICK ACTIVATED:");
console.log(this);
ev.stopImmediatePropagation(); // I tried this to solve the double click. ev is undefined.
... rest of code ...
select_item_2(this);
}function select_item_2(element) {
console.log("SELECTING ITEM 2");
... get data ...
console.log("ATTEMPTING TO POST ...");
$.post( ... );
}控制台输出:
CLICK ACTIVATED:
<div class="option-selection" data-value="5">…</div>
SELECTING ITEM 1
CLICK ACTIVATED:
<div class="option-selection" data-value="21">…</div>
SELECTING ITEM 2
ATTEMPTING TO POST ...
CLICK ACTIVATED:
Window {parent: Window, opener: null, top: Window, length: 1, frames: Window, …}
Uncaught TypeError: Cannot read property 'stopImmediatePropagation' of undefined
at 1:133
at i (jquery.min.js:2)
at qt (jquery.min.js:2)
at qt (jquery.min.js:2)
at Object.<anonymous> (jquery.min.js:2)
at Function.each (jquery.min.js:2)
at qt (jquery.min.js:2)
at qt (jquery.min.js:2)
at qt (jquery.min.js:2)
at qt (jquery.min.js:2)你知道这里发生了什么以及如何修复它吗?我知道我可以检查元素是否是dom对象(我找到了一个函数),但这看起来不应该像这样首先触发。
发布于 2020-10-04 22:11:05
试试下面的代码。
var option_1;
$(".option-selection").click(function(ev) {
if(option_1) { // Check if first option selected
if(option_1 == $(this)[0]) { // Check if first selected item is not the current item
console.log("Option already selected.");
} else {
console.log("2 different options selected.");
// Run your POST call here
// Once your post call is done you can reset the option_1 value, so that users can select other option for next round if needed
option_1 = null;
console.log("Options reseted");
}
} else {
option_1 = $(this)[0];
console.log("New Option.");
}
});.option-selection {
cursor: pointer;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="option-selection" data-value="1">Option 1</div>
<div class="option-selection" data-value="2">Option 2</div>
<div class="option-selection" data-value="3">Option 3</div>
<div class="option-selection" data-value="4">Option 4</div>
https://stackoverflow.com/questions/64195355
复制相似问题