简体   繁体   English

切换元素不适用于jQuery

[英]toggle element doesn't work with jQuery

I'd like to execute a JQuery toggle function (it toggles an input field to make it accessible to the client) only if a certain condition is met. 我只想在满足特定条件的情况下执行JQuery切换功能(它会切换输入字段以使其可被客户端访问)。 (I'm testing for the condition using JavaScript.) Can I do this? (我正在使用JavaScript测试条件。)可以这样做吗? For some reason, the JQuery toggle function doesn't work when I set it inside the JavaScript function, so I'm not sure if I'm doing something wrong, or if this can't be done at all. 出于某种原因,当我在JavaScript函数中设置JQuery切换功能时,该功能无法正常工作,因此无法确定自己做错了什么还是根本无法完成。

<script type="text/javascript">
function conditionalToggle()
{
   if (conditionIsMet)
   {
      // JQuery toggle call here
   }
}
</script>

You probably don't use jQuery right, or don't execute the function, or (the most common mistake of new jQuery users) don't wait for the DOM to be ready: 您可能不正确使用jQuery,或者不执行该函数,或者(新jQuery用户最常犯的错误)不要等待DOM准备就绪:

function foo(){
    if ("foo" === "foo")
        $('#elementId').toggle();
}

$(function(){ // functions inside $() runs after the DOM is ready.
    foo();
});

Where elementId is a place holder to your element id. 其中elementId是元素ID的占位符。
Simple DEMO 简单的演示


Note that you can use this toggle overload: 请注意,您可以使用以下toggle过载:

$('#elementId').toggle(showTheElementOrNot);

toggle( showOrHide )
showOrHide A Boolean indicating whether to show or hide the elements. showOrHide一个布尔值,指示是否显示或隐藏元素。

jQuery docs jQuery文档

jQuery should work if inside a ready() function 如果在ready()函数中,jQuery应该可以工作

<script type="text/javascript">
$(function() {
   function conditionalToggle(){
      if (conditionIsMet) {
         $(element).toggle();
      }
   }
});
</script>

or just do: 或只是做:

<script type="text/javascript">
    function conditionalToggle() {
       if (conditionIsMet) {
          element.style.display = element.style.display=='block' ? 'none' : 'block';
       }
    {
</script>

You can do it when DOM is ready, if you've still problem, you can do also like that: 您可以在DOM准备就绪时执行此操作,如果仍然遇到问题,也可以这样做:

<script type="text/javascript">
   $(window).load(function() {
        conditionIsMet && $('#elementId').toggle();
   });
</script>

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

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