开发者

Why is this jQuery code not working?

I am trying to make a simple tool tip function (I'm trying to learn jQuery so please don't suggest plugins for this). When I write it like this开发者_如何学编程 it works:

             $('span.toolTip').hide();
             function toolTip() {
                $('.targetLink').mouseover(function() {                
                    $('.toolTip').show().html('Hello there');
                });
            }

            <span class='toolTip'></span>
            <a href="#" class="targetLink">Hover over me</a>

But when I try to pass parameters through the function it doesn't work:

    $('span.toolTip').hide();
    function toolTip(target, tooltip, message) {
        var target = '.' + target;
        $(target).mouseover(function() {
            var tooltip = '.' + tooltip;
            $(tooltip).show().html(message);
        });
    }

    toolTip('targetLink', 'toolTip', 'Hello There');

    <span class='toolTip'></span>
    <a href="#" class="targetLink">Hover over me</a>


You're "hiding" the target parameter with a new local target variable:

function toolTip(target, tooltip, message) {
    // this target is not the same as the parameter target
    var target = '.' + target;

Simply remove the var and it should work:

function toolTip(target, tooltip, message) {
    target = '.' + target;
    ...


Your code is not working because variable tooltip is undefined.

$(target).mouseover(function() {
    var tooltip = '.' + tooltip;
    alert(tooltip); //undefined
    $(tooltip).show().html(message);
});

See error in jsfiddle.

EDIT

You're getting undefined, as @nick said, because you're creating a new local variable using the keyword var in var tooltip. So, to fix, remove var and you will get the external variable (closure).

See correct code in jsfiddle.

$(target).mouseover(function() {
    tooltip = '.' + tooltip;
    $(tooltip).show().html(message);
});


You're not getting the right .class selector since the variable is undefined, it should be:

function toolTip(target, tooltip, message) {
    $('.' + target).mouseover(function() {
        $('.' + tooltip).show().html(message);
    });
}

Currently you're creating a new variable...not resulting in the correct selector. You can test the updated/working version here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜