简体   繁体   中英

Parameters in functions (jquery/dialog)

I'm trying to use the same function for multiple links. Here's my code.

<a class="col-md-4 nieuws-item btn" href="javascript: void(0)" onclick="showDialog(dialog1); return false;" type="black">
    <p>sometext</p>
</a>

<a class="col-md-4 nieuws-item btn" href="javascript: void(0)" onclick="showDialog(dialog2); return false;" type="black">
    <p>sometext</p>
</a>

-

function showDialog(dialogname)
{
    $("#" + dialogname).dialog({
        modal: true,
        resizable: false,
        closeOnEscape: true
    });
}

-

<div id="dialog1" title="SIM Beurs 2015" style="display: none;">
    <p>test</p>
</div>


<div id="dialog2" title="SIM Beurs 2015" style="display: none;">
    <p>test</p>
</div>

Am I looking in the right direction? If so, where is my mistake?

You're missing some quotes:

onclick="showDialog('dialog1'); return false;"
                    ^here   ^and here

Same for dialog2 .

This problem does not occur (and would be more obvious) if you avoid inline onclick= handlers and just use jQuery handlers. That would also keep the code with the handler.

This has the advantage of allowing multiple handlers per item and does not avoid some of the other cool events features jQuery provides.

eg

<a class="col-md-4 nieuws-item btn" data-dialog="dialog1" href="javascript: void(0)" type="black">
    <p>sometext</p>
</a>

<a class="col-md-4 nieuws-item btn" data-dialog="dialog2" href="javascript: void(0)" type="black">
    <p>sometext</p>
</a>

and use a jQuery handler like this:

$('.nieuws-item.btn').click(function(){
    var dialogname = $(this).data('dialog');
    $("#" + dialogname).dialog({
        modal: true,
        resizable: false,
        closeOnEscape: true
    });
    return false;
});

or, if the elements are added dynamically, use a delegated handler:

$(document).on('click', '.nieuws-item.btn', function(){
    var dialogname = $(this).data('dialog');
    $("#" + dialogname).dialog({
        modal: true,
        resizable: false,
        closeOnEscape: true
    });
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM