【问题标题】:How to get sum of custom attributes in jquery如何在jquery中获取自定义属性的总和
【发布时间】:2020-01-30 19:20:31
【问题描述】:

我正在尝试检索自定义属性“mrbvalue”的值。 html是我在数据库中输入数据后sharepoint给我的。所以我不能添加我自己的课程或改变任何东西。 console.log() 只是我看看它是否有效。该代码有效,但是当我单击单选按钮的“否”和“有时”时,控制台会打印“是”值。

<tr>
                <td> <span>P1</span> </td>
                <td> <div class="n-mrb n-choice tbl" nfield="td_p1" value="1">

        <div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="Yes"> Yes</label></div>

        <div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="No"> No</label></div>

        <div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="Sometimes"> Sometimes</label></div>

    </div> 
 </td>
</tr>



$(".mrb-item").click(function() {
    var checkboxes = $(".mrb-item");

    for(var i =0; i < checkboxes.length; i++){

    if($('input').attr("mrbvalue")  == "Yes" ){
        console.log("yes");
        }
    }
    if($('input').attr("mrbvalue")  == "No" ){
        console.log("No");
        }
    }
    if($('input').attr("mrbvalue")  == "Sometimes" ){
        console.log("Sometimes");
        }
    }
})

【问题讨论】:

  • 当您使用$('input').attr("mrbvalue") == "Yes" 时,您基本上总是得到第一个输入。无论for 循环如何,您都需要使用eq 之类的东西。我发布了一个答案。

标签: jquery html sharepoint


【解决方案1】:

修改代码如下。

<table>
<tr>
<td> <span>P1</span> </td>
<td> <div class="n-mrb n-choice tbl" nfield="td_p1" value="1">
<div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="Yes"/> Yes</label></div>
<div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="No"/> No</label></div>
<div class="mrb-item"><label><input type="radio" name="td_p1"  mrbvalue="Sometimes"/> Sometimes</label></div>
</div> 
</td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
    $(".mrb-item input").click(function() {
        var mrbValue=$(this).attr("mrbvalue");
        if(mrbValue== "Yes" ){
            console.log("yes");
        }
        if(mrbValue== "No" ){
            console.log("No");
        }
        if(mrbValue== "Sometimes" ){
            console.log("Sometimes");
        }
    });
});
</script>

【讨论】:

    【解决方案2】:

    问题在于您的 if 语句,每次循环时,您总是会得到第一个输入。您需要使用eq

        // This is wrong
        if($('input').attr("mrbvalue")  == "No" ){
            console.log("No");
        }
    
        // This is right
        if($('input').eq(i).attr("mrbvalue")  == "No" ){
            console.log("No");
        }
    

    【讨论】:

      【解决方案3】:
      • jQuery: $('input[name="td_p1"]:checked').attr('mrbvalue')
      • 纯javascript:document.querySelector('input[name="td_p1"]:checked').getAttribute('mrbvalue')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-03
        • 2019-05-20
        • 2010-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多