javascript - 将 2 个 jQuery 函数合并为 1 个并保持点击顺序

标签 javascript jquery html

我正在尝试结合下面的这两个 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/

相关文章:

javascript - 修改嵌套对象,然后返回修改后的父对象

javascript - 无法更改 jquery 进度条圆圈的数据百分比标记 (%) 大小

javascript - 向页面添加大量元素时性能不佳

html - 当容器元素被内联元素填充时,浏览器如何决定是开始新行还是扩展容器?

javascript - 用 .innerText 缓慢更新样式表的内容

javascript - 使用 JavaScript 或 jQuery 将焦点设置为动态创建的 DIV

javascript - 有没有办法在 jQuery Datepicker 上同时使用相对和绝对年份范围?

html - 将 <li> 文本与列表图像对齐

javascript - 从 <div> 中的数组生成 <li>

javascript - 检测点击的url中是否有hash值