0

I am really new to javascript objects.

Here is my code:

(function(){
var homenavmenu = {
    nav:$('.navMenuButton'),
    target:$(this).attr('href'),
    test:function(){
        // alert(homenavmenu.target)
        homenavmenu.nav.click(function(){
            alert(1);
            return false;
        })
    }
}

homenavmenu.test();
})()

Why doesn't it work? It won't alert(1);

Here is my HTML:

<div class="navMenu">
  <a href="../market" class="navMenuButton" id="mo">market</a>
  <a href="../unit" class="navMenuButton" id="unit">my</a>
</div>
7
  • show you html as well man,? your function does shows alert without homenavmenu.... Commented Jul 11, 2012 at 5:01
  • it should be fine jsfiddle.net/aWgqk Commented Jul 11, 2012 at 5:04
  • You're missing your $ at the front of your dom ready method :) Commented Jul 11, 2012 at 5:11
  • no after i add the $ sign the firebug shows a error says $(function(){}()is not a function Commented Jul 11, 2012 at 5:15
  • $(function() { /* code here */ }); Commented Jul 11, 2012 at 5:16

2 Answers 2

2

Working Demo http://jsfiddle.net/5JmdD/3/

PLease check your html again, demo is working with what you need.

Behavior: click on the button and you will get alert.

Hope this helps :)

code

$(function(){
var homenavmenu = {
    nav:$('.navMenuButton'),
    target:$(this).attr('href'),
    test:function(){
        // alert(homenavmenu.target)
       homenavmenu.nav.click(function(){
            alert(1);
            return false;
        })
    }
}

homenavmenu.test();
})()​

HTML

<input type="button" value="hulk" class="navMenuButton" />​
Sign up to request clarification or add additional context in comments.

10 Comments

with my html its not working,after click the <a> the page reload to the href, still won't alert
@chenliang no worries man :) flick you html or better yet chuck it in jsfiddle I will take a look,
@chenliang -- here you go jsfiddle.net/JRwY2/3 -- two things to note. When using jsFiddle you must load the library (dropdown menu, left) of jQuery to run the jQuery library. $ is not a function, unless you have the jQuery library installed (or another library using the $). Also, you need to use (function($){ to begin and })(jQuery) to end if you wish to protect your function.
@Tats_innit--thanx man, really appreciate your help. it work in jsfiddle but not work on local. i will keep on looking the error ,but again thank you so much
@chenliang Glad I can help man! jsfiddle.net/rwJW9 :)) hmm check something must be wrong in th HTML bruv
|
0

ok it seems like you can't use

nav:$('.navMenuButton'),

should use

nav:'.navMenuButton',

invoke as

$(homenavmenu.nav).click(function(){
   alert(1)
})

this work for me,but i don't know why it worked in the example above.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.