我有两个 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/