下面是在div点击时触发隐藏按钮点击事件的代码。但是当我单击div时,按钮单击事件将进入无限循环。所以请让我知道如何解决这个问题:
$(document).ready(function() {
$('#newDiv').click(function() {
$("#button1").on("click", function() {
console.log("in onclick");
}).click();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newDiv"><button id="button1" hidden>Submit</button></div>
答案 0 :(得分:1)
不要在div单击内绑定按钮单击,否则每次单击div时都将绑定一个新事件,将其绑定到外部,而只需在div单击中调用单击即可。
// bind this outside the div click event
$("#button1").on("click", function() {
console.log("in onclick");
});
$('#newDiv').on("click", function() {
$("#button1").get(0).click(); // I prefer to use click action on the native js object - seems to work better than the jquery click action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="newDiv">
<button id="button1" hidden>Submit</button>
click in div
</div>
答案 1 :(得分:-1)
.get()方法授予对每个jQuery对象基础的DOM节点的访问权限。如果#include<iostream>
#include<map>
#include<string>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
unordered_map<string, vector<string>> Mymap;
Mymap["unique1"] = { "hello", "world" };
Mymap["unique2"] = { "goodbye", "goodmorning", "world" };
Mymap["unique3"] = { "sun", "mon", "tue" };
// Case 1
string test_value = "goodmorning";
auto iter1 = find_if(Mymap.begin(), Mymap.end(),
[&test_value](const decltype(*Mymap.begin()) &pair)
{
return any_of(pair.second.begin(), pair.second.end(), [&test_value](const string& str) { return str == test_value; });
});
if (iter1 != Mymap.end())
{
cout << "Key: " << iter1->first << endl;
}
else
{
cout << "No key found for " << test_value;
}
// Case 2
test_value = "unique3";
auto iter2 = Mymap.find(test_value);
if (iter2 != Mymap.end())
{
int first = true;
for (auto v : iter2->second)
{
cout << (first ? "" : ", ") << v;
first = false;
}
cout << endl;
}
else
{
cout << "No value found for key " << test_value << endl;
}
return 0;
}
的值超出范围-小于元素的负数或等于或大于元素的数量-则返回index
。
undefined
$('#newDiv').on('click', function(event) {
$('#btnHidden').get(-1).click();
});
$("#btnHidden").on("click", function() {
console.log("Hidden Button Clicked");
});
#newDiv {
border: 1px solid red;
padding: 10px;
}