gpt4 book ai didi

javascript - jQuery - 改变样式和显示某些元素

转载 作者:行者123 更新时间:2023-11-28 02:11:39 25 4
gpt4 key购买 nike

看来我对 Javascript 的了解足以伤害到自己,所以我来这里向你们寻求帮助。这是我正在尝试做的事情和我的问题。

我有两份表格,根据用户的选择只会填写一份。他们将单击一个按钮或另一个。当他们单击按钮时,表单淡入并且按钮更改类(从浅色按钮变为深色按钮)这是我遇到的问题。首先,我根本无法让表单淡入淡出,如果我点击按钮两次而不是一次,按钮只会更改类。

另一件我不确定如何去做的事情是,如果我说选择了表格 1,但我想单击表格 2,那么我希望表格 1 淡出,表格 2 淡入并且按钮相应地改变。这是我的代码:

JS

<script type="text/javascript">
var $j = jQuery.noConflict();
var $jtest1 = $j('#test1');
var $jtest2 = $j('#test2');

$j("#button1").live('click',function(){
//Fade out form if shown and fade in form selected
$jtest2.fadeOut("slow", function(){
$jtest1.fadeIn("slow");
});
$j('#button1').live('click', function(){
//change class from light to dark
$j(this).addClass('dark_button').removeClass('light_button');
}); //I need to change this class to light if
// button 2 is selected and change button 2 to dark
});
</script>

HTML

<p class="light_button" id="button1">Test 1 </p>
<p class="light_button" id="button2">Test 2 </p>


<div class="hide" id="test1"><p>TEST</p></div>
<div class="hide" id="test2"><p>TEST 2</p></div>

Note: class="hide" is style="display:none"

感谢您的帮助,因为我很困惑,不确定是否要解决这个问题。另外请给我一个例子,因为当有人说把这个改成那个等等时,我并不总是听从。

最佳答案

看下面的代码,添加注释说明原因

$j("#button1").live('click',function(){  
//Fade out form if shown and fade in form selected
$jtest2.fadeOut("slow", function(){
$jtest1.fadeIn("slow");
});

//The following is inside the click so I do not get added until the first click
//and added after every click so I multiply!
//Hence why it takes 2 clicks

$j('#button1').live('click', function(){
//change class from light to dark
$j(this).addClass('dark_button').removeClass('light_button');
}); //I need to change this class to light if
// button 2 is selected and change button 2 to dark
});

你应该这样做

$j("#button1, #button2").live('click',
function(){

//figure out what button was clicked.
if(this.id === "button1"){
var btnA = $j(this);
var btnB = $j("#button2");
var divA = $j('#test1');
var divB = $j('#test2');
}
else{
btnA = $j(this);
btnB = $j("#button1");
divA = $j('#test2');
divB = $j('#test1');
}

//make sure it is not already active, no use to show/hide when it is already set
if(btnA.hasClass('dark_button')){
return;
}

//see if div is visible, if so hide, than show first div
if(divB.is(":visible")){
divB.fadeOut("slow", function(){
divA.fadeIn("slow");
});
}
else{//if already hidden, just show the first div
divA.fadeIn("slow");
}

//Add and remove classes to the buttons to switch state
btnA.addClass('dark_button').removeClass('light_button');
btnB.removeClass('dark_button').addClass('light_button');
}
);

jsfiddle example

关于javascript - jQuery - 改变样式和显示某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7975480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com