php - jquery 在两个 View 之间切换

标签 php javascript jquery

我有两个 div,id 分别是今天明天。由于只能显示其中一个,我编写了一个 JavaScript 函数来在这两个之间切换。

    function switchDay(selector) {
    if (selector == "tomorrow") {
        $("#today").hide();
        $("#tomorrow").show();
        $("#daySelector").html('<a href="#" onclick="return switchDay(\'today\');">this day</a> | next day');

    }
    if (selector == "today") {
        $("#tomorrow").hide();
        $("#today").show();
        $("#daySelector").html('this day | <a href="#" onclick="return switchDay(\'tomorrow\');">next day</a>');

    }   
  return false;
}

在我的 PHP 中,我回显开关链接,如下所示:

echo '<p id="daySelector">today | <a href="#" onclick="return switchDay(\'tomorrow\');">tomorrow</a></p>';

如您所见,我已经将 hide() 和 show() 切换为 jquery 函数(在使用 .style.display 函数之前),现在还想放弃旧的 onclick 和而是使用 jquery .click()。不过,我不确定如何更改开关链接。

我该怎么做? (最好是它不会使我的脚本变得更大......)

最佳答案

有很多方法可以实现这一点(天哪,我因此喜欢编程)。

一个简单的方法是这样做:

$('#daySelector a').live('click', function () {
    if ($(this).hasClass("tomorrow")) {
        $("#today").hide();
        $("#tomorrow").show();
        $("#daySelector").html('<a href="#" class="today">this day</a> | next day');    
    }
    if ($(this).hasClass("today")) {
        $("#tomorrow").hide();
        $("#today").show();
        $("#daySelector").html('this day | <a href="#" class="tomorrow">next day</a>');

    }   
  return false;
});

然后像这样执行 PHP:

echo '<p id="daySelector">today | <a href="#" class="tomorrow">tomorrow</a></p>';

我没有测试过。应该仍然可以工作。

下面的评论让我想起了 live 已被弃用。这是使用 .on 方法的方式。我也进行了编辑,避免使用文档进行绑定(bind)。

$('#daySelector').on('click', 'a', function () {
    if ($(this).hasClass("tomorrow")) {
        $("#today").hide();
        $("#tomorrow").show();
        $("#daySelector").html('<a href="#" class="today">this day</a> | next day');    
    }
    if ($(this).hasClass("today")) {
        $("#tomorrow").hide();
        $("#today").show();
        $("#daySelector").html('this day | <a href="#" class="tomorrow">next day</a>');

    }   
  return false;
});

关于php - jquery 在两个 View 之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12736185/

相关文章:

php - jquery 追加复选框,如果选中,它不会返回任何东西?

javascript - 如何预加载 Javascript/JQuery/HTML 对话框

php - 从生成的 HTML 表中删除一行

php - Magento 和可配置的产品属性

javascript - jQuery Ajax 无限滚动阅读 PHP

javascript - async.mapLimit 使用来发出多个请求

javascript - 如何将值数组作为键分配给另一个值数组?

javascript - 使用 jquery 从 iframe 更新父级

php - 在自定义插件错误问题中扩展 WC_Product 类(找不到 WC_Product 类)

php - 在 Zend 中创建表单 View