简体   繁体   English

jQuery中的javascript切换无法按预期工作

[英]javascript toggle in jquery not working as expected

I have a button which toggles an iframe on and off using just javascript. 我有一个仅使用JavaScript即可打开和关闭iframe的按钮。

But when i click the button, instead of just iframe disappearing, the button also disappears along with iframe. 但是,当我单击按钮时,按钮不仅随iframe消失,而且随iframe一起消失。

While checking in the firebug console, the CSS of the button also changes display parameter to 'none'. 在Firebug控制台中签入时,按钮的CSS还将显示参数更改为“无”。

$(document).ready(function(){

    var iDiv = document.createElement('div');
    iDiv.id = 'enigma';
    iDiv.setAttribute("style", "font-size:18px;position:fixed;bottom:20px;right:5px;display:inline");
    document.body.appendChild(iDiv);

    var div = document.createElement("div");
    div.innerHTML = '<iframe src="http://example.com/index.html" width="400" height="200" style="border:0"></iframe>';
    iDiv.appendChild(div);

    var div2 = document.createElement("div");
    div2.setAttribute("style","display:inline;");
    div2.innerHTML = '<button id="button2">Show/Hide</button>';
    document.body.appendChild(div2);

    setTimeout(function() {
        $("#button2").css({"position": "fixed", "display": "inline", "bottom": "0", "right": "0"}).click(function(){
            $("div").toggle('show');
        });
    }, 100);
});

When you click the button, you run 单击按钮后,运行

$("div").toggle('show');

which toggles all of the div s in the page. 这会切换页面中的所有div This includes the one containing the button. 这包括一个包含按钮的按钮。 You can add an id to the div you want to hide to make it work: 您可以向要隐藏的div添加一个ID,以使其正常工作:

var div = document.createElement("div");
div.id = "to-toggle";
...
setTimeout(function() {
    $("#button2").css({"position": "fixed", "display": "inline", "bottom": "0", "right": "0"}).click(function(){
        $("#to-toggle").toggle('show');
    });
}, 100);

$("div").toggle('show'); toggles all <div> elements. 切换所有 <div>元素。

Perhaps you want 也许你想要

$("iframe").toggle('slow');

Or be more specific and add an id to the element you are trying to control as per Iluvatar's answer 或者更具体一些,并按照Iluvatar的回答在您要控制的元素上添加一个id

You need to be more specific here... 您需要在这里更具体...

$("div").toggle();

You are currently targeting every div tag. 您目前定位每个div标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM