开发者

JavaScript OnClick Handler Not Invoking

开发者 https://www.devze.com 2022-12-29 16:29 出处:网络
I\'m calling a javascript function in an inline onclick like so: <a href=\"#\" onclick=\"removeAttribute(\'foo\', \'bar\');\">Some Link</a>

I'm calling a javascript function in an inline onclick like so:

<a href="#" onclick="removeAttribute('foo', 'bar');">Some Link</a>

When I click on the link, though, nothing happens. I have other links (to other functions) tied to onclicks that work fine elsewhere on the same page. All links to this "removeAttribute" function fail.

There are no errors in Firebug, and the onclick event handler is being invoked - but stepping into the removeAttribute function ends up, for some reason, somewhere in jQuery.js. At no point does remov开发者_如何学编程eAttribute ever get called.

If I do:

javascript:removeAttribute('foo', 'bar');

in Firefox's address bar. The function is called successfully.

Anyone seen this?


Are you calling your own method? If so it is confusing to call it removeAttribute because it is already defined as method attached to DOM nodes. When your event handler is called its scope is defined as the Node that was clicked. Your code is probably calling the builtin method on the object the was clicked. Try using a different name or putting your method inside of a Javascript object so you can call it explicitly.


Try this:

<a href="javascript:removeAttribute('foo', 'bar');">Some Link</a>

It probably isn't working because of the '#' for the href value. So instead put the javascript as the href, which effectively is the same thing as putting it in the address bar.


If you're using jQuery, why not leverage it? Assuming your version of removeAttribute() does the same thing as the native javascript method removeAttribute(), you could do something like:

<script type='text/javascript'>
    $(document).ready(function(){
        $('a#somelink').click(function(){
            $('#foo').removeAttr('bar');
        });
    });
</script>
0

精彩评论

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