jquery 文本切换 onclick
jquery text toggle onclick
这可能是一个愚蠢的问题,但我才刚刚开始学习,所以请耐心等待:) ...请问为什么这个文本切换不起作用?
$(document).ready(function(){
textSwap();
$("#showHi").on("click", textSwap);
$("#showBye").on("click", textSwap);
});
var isHi = false;
function textSwap() {
if (isHi) {
$("#text").html("<a href='#' id='showHi'>Bye</a>");
}
if (!isHi) {
$("#text").html("<a href='#' id='showBye'>Hi</a>");
}
isHi = !isHi;
}
和:
<div id="text">some text</div>
$(document).ready(function(){
textSwap();
var isHi = false;
$("#showHi").on("click", textSwap);
$("#showBye").on("click", textSwap);
});
function textSwap() {
if (isHi) {
$("#text").html("<button id='showHi'>Bye</button>");
}
else{
$("#text").html("<button id='showBye'>Hi</button>");
}
isHi = !isHi;
}
发生这种情况是因为您用 de $("#text").html...
覆盖了原来的 HTML
尝试
$(document).ready(function(){
textSwap();
});
var isHi = false;
function textSwap() {
console.log(isHi);
if (isHi) {
$("#text").html("<a href='#' id='showHi'>Bye</a>");
$("#showHi").on("click", textSwap);
}
if (!isHi) {
$("#text").html("<a href='#' id='showBye'>Hi</a>");
$("#showBye").on("click", textSwap);
}
isHi = !isHi;
}
另一种简单的方法:
https://jsfiddle.net/07enc391/
由于 jQuery 中不再有 .live(或者不是 100% 确定已弃用),您必须使用 .on 这样就可以了
$("body").on("click", "#showHi", textSwap);
$("body").on("click", "#showBye", textSwap);
这可能是一个愚蠢的问题,但我才刚刚开始学习,所以请耐心等待:) ...请问为什么这个文本切换不起作用?
$(document).ready(function(){
textSwap();
$("#showHi").on("click", textSwap);
$("#showBye").on("click", textSwap);
});
var isHi = false;
function textSwap() {
if (isHi) {
$("#text").html("<a href='#' id='showHi'>Bye</a>");
}
if (!isHi) {
$("#text").html("<a href='#' id='showBye'>Hi</a>");
}
isHi = !isHi;
}
和:
<div id="text">some text</div>
$(document).ready(function(){
textSwap();
var isHi = false;
$("#showHi").on("click", textSwap);
$("#showBye").on("click", textSwap);
});
function textSwap() {
if (isHi) {
$("#text").html("<button id='showHi'>Bye</button>");
}
else{
$("#text").html("<button id='showBye'>Hi</button>");
}
isHi = !isHi;
}
发生这种情况是因为您用 de $("#text").html...
覆盖了原来的 HTML尝试
$(document).ready(function(){
textSwap();
});
var isHi = false;
function textSwap() {
console.log(isHi);
if (isHi) {
$("#text").html("<a href='#' id='showHi'>Bye</a>");
$("#showHi").on("click", textSwap);
}
if (!isHi) {
$("#text").html("<a href='#' id='showBye'>Hi</a>");
$("#showBye").on("click", textSwap);
}
isHi = !isHi;
}
另一种简单的方法: https://jsfiddle.net/07enc391/
由于 jQuery 中不再有 .live(或者不是 100% 确定已弃用),您必须使用 .on 这样就可以了
$("body").on("click", "#showHi", textSwap);
$("body").on("click", "#showBye", textSwap);