开发者

jQuery: using a variable as a substitute for a div?

开发者 https://www.devze.com 2023-03-21 06:49 出处:网络
Ooops, fiddle updated now correct In this fiddle, http://jsfiddle.net/SySRb/118/once you click .start an element from an array is randomly chosen and assigned to variable ranThis random selection jque

Ooops, fiddle updated now correct In this fiddle, http://jsfiddle.net/SySRb/118/ once you click .start an element from an array is randomly chosen and assigned to variable ran This random selection jquery has been checked http://jsfiddle.net/urfXq/96/ and is working so I don't think that's the problem, although people have suggested ways to make it more elegant.

Continuing on...

After the element from the array is assigned to ran, an if- then structure begins. The if is definitely false in this fiddle, so the else code should run. My intent with the else code is to add the div hash tag, and then do ran.show so that one of the two divs (hidden with css) on the page becomes visible.

The else isn't working. If the if statement were true, I assume it wouldn't work either...

else { 
                  ran = ('# + ran');
                  $('ran').show(); //one of the two divs should show but they don't
                  }

          });

Note, because this is just a piece of larger开发者_StackOverflow社区 code, if you totally restructure everything, I may not be able to use it...


You are doing the string concatenation wrong..

use

ran = '#' + ran;
$(ran).show();

and you need to call your test method on document.ready so use

$(test);

Demo at http://jsfiddle.net/gaby/SySRb/129/


A few things:

  1. You're forgetting to use $ to query the DOM with jQuery. You should replace:

    ran = ('# + ran');
    

    with

    ran = $("#" + ran");
    

    That is, build a jQuery selector by appending # to ran, then call jQuery with that selector.

  2. Since the variable you're saving the results of the jQuery call is called ran, you should replace

    $('ran').show();
    

    with

    ran.show();
    
  3. Does the function test() ever get called? Part of the reason you're code isn't working is because that function is not getting called, so the click event is never bound. Wrap the entire thing in $(document).ready(function () { ... }) and call test().

  4. Be sure to use var with your variable declarations. Otherwise, you're creating a global variable.

Here's your example fixed up: http://jsfiddle.net/andrewwhitaker/9BcUP/

0

精彩评论

暂无评论...
验证码 换一张
取 消