alden (3) [Avatar] Offline
#1
I am gradually working my way through chapter two and very much enjoying the book but I've come across a small problem which either indicates my naivete about the DOM, or about jQuery. . .

I tried to build a test case off of the click attribute from listing 2.1 and made the following test script:
$(document).ready(function() {
$('<button>hello</button>',
{
click: function(){
alert("Hello!");
}
})
.css({
cursor: 'pointer',
border: '2px solid black',
backgroundColor: 'red',
width: '200px',
})
.appendTo('body');});


When I tried to run this, nothing happened. But if I remove the "hello" from between the open and close button tags like so: '<button></button>', then everything works and clicking on the button does produce an alert.

What is going on?
alden (3) [Avatar] Offline
#2
Re: Listing 2.1 Puzzle
Okay, so I think I've figured out the issue with the help of some awesome folks over in jQuery's IRC channel. . . It seems to boil down to "stick with one method".

According to this:
https://github.com/jquery/jquery/blob/master/src/core.js#L121-123

it seems that the process I used is willing to accept either a tag with all it's properties already in place OR an empty tag which you then add properties to, but not both at once.

So this would work better:
$('<button></button>',
{
text: "Hello",
click: function(){
alert("hello");
}
})

Hope this helps someone else!
bear.bibeault (675) [Avatar] Offline
#3
Re: Listing 2.1 Puzzle
Beat me to it!

I was going to suggest just using "<button>" and adding all attributes, including content, later. That's the way I usually do it as I'm not a big fan of building up even moderately complex HTML in strings.