我有一些代码试图将 div 的 id 值传递给一个函数,然后该函数淡出第一个 div,然后淡入第二个 div。我知道该函数接收对象,因为当我尝试显示使用 $alert() 赋予它的值时,我得到 [Object object]。单击其中一个按钮时,它将尝试找到可见的 div 的 id,然后将其传递给 fade 函数,但是它会找到 id 并将其保存在一个字符串中,我需要将其转换为一个对象.这是我的代码:
<script type="text/javascript">
$(function() {
$('#step1').fadeIn("slow");
$('#btn1').addClass("btn-primary active");
$('#btn1').click(function() {
var id = $(".editor .steps").filter(function () { //this gets the value of the active div and saves it into id.
if ($(this).css('display') == 'block') {
return true;
}
}).attr('id');
fade(id, $('#step1')) //tyring to send id and the the step1 to the fade function
});
$('#btn-step2-video').click(function() {
fade($('#step1'), $('#step2-video'));
$('#btn1').addClass("btn-primary");
$('#btn2').addClass("btn-primary active");
});
$('#btn-step2-picture').click(function() {
fade($('#step1'), $('#step2-picture'));
btn2.addClass("btn-primary active");
});
var fade = function(fadeout, fadein){
$(fadeout).fadeOut("slow");
$(fadein).fadeIn("slow");
}
});
</script>
Here is the HTML of the page:
<!-- begin snippet: js hide: false -->
<div id="steps">
<button id="btn1" type="button" class="btn btn-primary btn-lg btn-step">1</button>
<a class="btn-description">Choose type of ad</a>
<button id="btn2" type="button" class="btn btn-primary btn-lg btn-step">2</button>
<a class="btn">Confirmation & Payment</a>
</div>
<!--
Begining of editor
-->
<div class="editor">
<!--
Step 1 of the editor
-->
<div id="step1" class="steps" style="display:none;" >
<a id="btn-step2-video" style="position:fixed; top: 45%; left: 25%; cursor:pointer"><div class="btn-ad-choice ad-choice">
<br>
<p><b>Create a video ad:</b></p>
<video width="200" height="113" autoplay="autoplay" mute>
<source src="video/exemple.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div></a>
<a id="btn-step2-picture" style="position:fixed; top: 45%; right: 25%; cursor:pointer"><div class="btn-ad-choice ad-choice">
<br>
<p><b>Create a picture ad:</b></p>
<img src="images/adexemple.jpg" alt="Exemple of a picutre ad" height="113" width="200">
</div></a>
</div>
<!--
Step 2 for video of the editor
-->
<div id="step2-video" class="steps" style="display: none; height:400px; width:100%; background:gray">
video
</div>
<!--
Step 2 for pictures of the editor
-->
<div id="step2-picture" class="steps" style="display: none;">
picture
</div>
<!--
end of editor
-->
</div>
编辑
我将我的 javascript 编辑为:
$('#btn1').click(function() {
fade($(".editor .steps:visible"), $('#step1')); //tyring to send id and the the step1 to the fade function
});
推荐人:Arun P Johny 谢谢 ;)
最佳答案
jQuery 对象也接受选择器,所以我能看到的唯一问题是您没有使用 id selector ,您正在传递 id 并将其用作 element selector所以
fade('#'+id, $('#step1'))
应该可以。
但是您可以使用 visible selector 来简化它到
$('#btn1').click(function () {
fade($(".editor .steps:visible"), $('#step1')) //tyring to send id and the the step1 to the fade function
});
关于javascript - Jquery 字符串转对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666672/