jquery 移动按钮文本通过点击在两个文本之间切换

jquery mobile button text switching between two text via click

我对 jquery 手机和按钮文本切换有疑问。

每次单击 sie 按钮时,按钮文本都会更改。它只工作一次。我单击按钮,文本和背景发生变化,第二次单击它时没有任何反应。这是我的代码:

按钮声明:

<div data-role="header">
    <div data-role="navbar">
      <ul>
        <li><a href="#" id="lock" class="lockaction" >Lock</a></li>
      </ul>
    </div>
  </div>

这里是我的函数:

$(".lockaction").click(function(e) { 

            if (e.target.id == "lock" ) {

                document.getElementById("lock").text = "Unlock";
                $(this).css("background-color", "red");

                }

            else {

                document.getElementById("lock").text = "Lock";

                }

        postupdate();

    });

也许有人可以帮助我。

您需要检查 text 包含什么值。您正在检查 id,它将始终 return 为真,因为 ID 不会更改,因此您的 if 始终为真。

$(".lockaction").click(function (e) {
    e.preventDefault();//prevent default action
    if ($(this).text() == "Lock") {
        $(this).text("Unlock");
        $(this).css("background-color", "red");

    } else {
        $(this).text("Lock");
        $(this).css("background-color", "white");
    }
    postupdate();

});

失败,因为您的 ID 始终是 "lock"。改为检查元素中的文本。

尝试这样的事情:

$(".lockaction").click(function(e) { 

    e.preventDefault();

    if ($(this).text() === "Lock" ) {
        $(this).text("Unlock");
        $(this).css("background-color", "red");
    } else {
        $(this).text("Lock");
        $(this).css("background-color", "white");
    }

    postupdate();

});

Fiddle.