将Jquery用于基于属性值字符串的IF语句

时间:2018-08-20 02:02:22

标签: jquery html

我正在使用此元素

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" state="login">

和脚本

$("#toggleLogin").click(function() {

    if ($("#exampleModal").data("state") === "login") { alert("it works"); } else { alert ("not working");};



<script `src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" crossorigin="anonymous"></script>`

我希望有一个脚本,如果“ state”的值是“ login”,它将切换为“ signup”,否则将再次“ login”

我在这里找到了这个示例,但是对我来说不起作用

Check if data attribute value equals a string

1 个答案:

答案 0 :(得分:1)

重新排序脚本以预先包含jQuery。然后将state="login"标记中的data-state="login"更改为#exampleModal

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" crossorigin="anonymous"></script>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-state="login"></div>

<button id="toggleLogin">Toogle Login</button>


<script>
$("#toggleLogin").click(function() {

    if ($("#exampleModal").data("state") === "login") {
        $("#exampleModal").data("state", "signup");
    } else {
        $("#exampleModal").data("state", "login");
    }
    console.log($("#exampleModal").data("state"));
    
});
</script>