I'm having trouble firing a click event on an . When insertIntoInsertHolder() is called it adds a link to the content of div#swf_insert_holder - I then create the click event just below. However the event doesn't fire.
$javascript = "javascript:;";
$swf_insert_box_link = "swf_insert_box_link";
echo "
function insertIntoInsertHolder( filename ) {
$('#swf_insert_holder').append('<a href=" . $javascript . " class=" . $swf_insert_box_link . ">go</a>');
//produces: <a href="javascript:;" class="swf_insert_box_link">go</a>
}
$('a.swf_insert_box_link').click( function() {
alert('hello!!'); //for test开发者_StackOverflow社区ing
});
Thanks in advance!
It also has to be noted, that event handlers are attached to existing elements. So, when your 'click' event is attached to a.swf_insert_box_link, the element should exist. In order to have event attached to the given existing selector and for any new elements matching the same selector, user live() - http://api.jquery.com/live/
Using this will cause it to work:
<?php
$javascript = "javascript:;";
$swf_insert_box_link = "swf_insert_box_link";
echo <<<JS
function insertIntoInsertHolder( filename ) {
\$('#swf_insert_holder').append('<a href="$javascript" class="$swf_insert_box_link">go</a>');
// produces: <a href="javascript:;" class="swf_insert_box_link">go</a>
}
\$('a.swf_insert_box_link').live('click', function() {
alert('hello!!'); //for testing
});
JS;
?>
The important parts were #1, fixing all PHP syntax errors and #2, using live
instead of click so you can define the event callback before the element actually exists.
element must exist before attaching event listeners. you can do it with live() function instead of click() (requires jquery 1.3+), or bind it while creating element, like this:
function insertIntoInsertHolder( filename ) {
$('#swf_insert_holder').append(
$('<a>')
.attr('href', '<?php echo $javascript; ?>')
.addClass('<?php echo $swf_insert_box_link;?>')
.text('go')
.click(function() { alert('hello!!'); });
);
}
精彩评论