试图从2个不同的跨度获得2个值

时间:2016-11-22 04:16:34

标签: javascript jquery html

嘿伙计们我试图从2个不同的范围获得2个值。我有几个桌子上有betslip和赌注数量赔率,而我想要做的就是获取名称和赌注赔率并将其存储到jquery中的变量然后我将其推送到betslip。我唯一的问题是我似乎无法获得正确的值。这是HTML:

<td>
    <a href="#" id="bet">
        <span id="betslip">Lautoka FC</span> 
        <span id="betnum"> 5/6</span>
    </a>
</td>
<td>
    <a href="#" id="bet">
        <span id="betslip">Draw</span>
        <span id="betnum">11/5</span>
    </a>
 </td>

这是我的jquery代码:

$(document).ready(function() {
    $('#betslip, #betnum').click(function() {
    var bet = $(this).text();
    var num = $(this).text();
    alert("name: " + bet + "num: " + num);
    });


});

我得到了错误的价值观。谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

this将引用单击的元素。如果需要两个值,则可能需要再次选择元素。如果有多个组合的场景,您可以使用类。

示例代码段:

&#13;
&#13;
$(document).ready(function() {
  $('.bet').click(function() {
    var bet = $(this).find(".betslip").text();
    var num = $(this).find(".betnum").text();
    console.log("name: " + bet + " num: " + num);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
  <a href="#" class="bet">
    <span class="betslip">Lautoka FC</span> 
    <span class="betnum"> 5/6</span>
  </a>
</td>
<td>
  <a href="#" class="bet">
    <span class="betslip">Draw</span>
    <span class="betnum">11/5</span>
  </a>
</td>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这会对你有帮助,

$(document).ready(function() {
    $('#betslip, #betnum').click(function() {
        var id = $(this).attr("id");

        if(id == "betslip"){
            var bet = $(this).text();
            var num = $("#betnum").text();
        }else{
            var bet = $("#betslip").text();
            var num = $(this).text();
        }
        alert("name: " + bet + "num: " + num);
    });
});

答案 2 :(得分:0)

试试。点击单element时只传递。不带两个元素

$(document).ready(function() {
    $('#betslip, #betnum').click(function() {
    var bet = $('#betslip').text();
    var num = $('#betnum').text();
    alert("name: " + bet + "num: " + num);
    });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><a href="#" id="bet">
  <span id="betslip">Lautoka FC</span> <span id="betnum"> 5/6</span></a></td>