超链接onclick功能无法正常工作

时间:2014-05-09 15:31:03

标签: jquery html

我需要在超链接上处理onclick函数,但它不起作用..

HTML代码: -

<a href="#" onclick="updateParent()" id="2" value="2">CLICK HERE</a>

Jquery的: -

$(document).ready(function(){

    function updateParent(control) {
                    alert('Hi')
                }

})

http://jsfiddle.net/sbnBy/1/

2 个答案:

答案 0 :(得分:6)

updateParent仅存在于.ready()函数中。 onclick工作需要全球化。

此外,您不应该使用内联事件。你有jQuery,使用它。

<a href="#" id="2" value="2">CLICK HERE</a>

<script>
    $(document).ready(function(){
        $('#2').click(function(e){
            // preventDefault... it prevents the "default" action of the tag
            // In this case, it would try to nagivate to `#`.  Which would
            // scroll the page to the top.
            e.preventDefault();

            alert('hi');
        });
    });
</script>

答案 1 :(得分:2)

function应该在onclick的全球范围内工作。

删除除功能以外的所有内容:

function updateParent(control) {
  alert('Hi')
}

但是由于JsFiddle创建了一个闭包,上面的内容仍然无效。

所以最终的解决方案就是:

window.updateParent = function(control){
   alert("hi");
}

此外,您不需要内联js。使用

$(document).ready(function(){
    $('#2').click(function(e){
        e.preventDefault(); // prevent the default action such as redirecting.
        alert('hi');
    });
});

此外,您可以更改jsfiddle选项以使用 wrap in head