我正在尝试结合下面的这两个 jQuery 函数,并能够为第一次点击第一行图像和第一次点击第二行图像添加 ID 属性。
这是 jQuery 代码:
$(".first-row, .second-row").on("click", "img", function() {
//want ID1 to be for the first click of first row of images
ID1 = $(this).attr('id');
//want ID2 to be for the first click of the second row of images
ID2 = $(this).attr('id');
console.log(ID + " " + ID2);
});
// desired outcome "individual yes" or "family maybe" ect ect
这是我的 HTML 代码:
<html>
<head>
<meta name="description" content="example of selection order" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<title></title>
</head>
<body>
<div class="all-images">
<div class="first-row">
<div class="first-id">
<img src="image1.jpg" alt="Individual" id="individual">
</div>
<div class="second-em">
<img src="image2.jpg" alt="employer" id="employeer">
</div>
<div class="third-fa">
<img src="image3.jpg" alt="fam" id="family">
</div>
</div>
<div class="second-row">
<div class="yes-first">
<img src="image4.jpg" alt="yes" id="yes">
</div>
<div class="no-second">
<img src="image5.jpg" alt="no" id="yes">
</div>
<div class="maybe-third">
<img src="image6.jpg" alt="maybe" id="maybe">
</div>
</div>
</div>
</body>
</html>
就像我上面提到的,我只需要它来跟踪第一行的第一次点击和第二行图像的第一次点击的 ID 属性,并将它们组合起来,然后将结果打印到控制台。
最佳答案
var ID1, ID2;
$('.first-row img').click(function(e){
ID1 = this.id;
});
$('.second-row img').click(function(e){
if (!ID1) return;
ID2 = this.id;
// we have ID1 & ID2 populated--do something
console.log(ID1 + ' ' + ID2);
// last step: reset
ID1 = ID2 = null;
});
如果有意义,将事物组合起来很好。在这里,我只是分别绑定(bind)它们然后(基于是否点击了第一行)收集第二个 Id 并继续。
添加了视觉队列的演示:http://jsfiddle.net/wpCus/
关于javascript - 将 2 个 jQuery 函数合并为 1 个并保持点击顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889070/