Could not find element inside Datalist by ID with

2019-08-15 10:51发布

问题:

Below is a rendered Datalist. It seems that $('#ctl00_ContentPlaceHolder1_ShowListing_DataList1$3$0$enquire').click(function() { ... } does not work because when I click on one of the buttons (on the DataList) which are meant to trigger this function, nothing happens.

How do I use JQuery to find the buttons by ID? So basically the function should be triggered if any of those buttons on DataList is clicked.

Thank you.

    <table id="ctl00_ContentPlaceHolder1_ShowListing_DataList1" class="DataWebControlStyle"
        style="visibility: visible;">
        <tbody>
            <tr>
                <td class="RowStyle">
                    <div class="ListItemContainer">
                        <div class="EnquireButton">
                            <a class="activator" id="ctl00_ContentPlaceHolder1_ShowListing_DataList1$3$1$enquire">
                            </a>
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td class="RowStyle">
                    <div class="ListItemContainer">
                        <div class="EnquireButton">
                            <a class="activator" id="ctl00_ContentPlaceHolder1_ShowListing_DataList1$3$1$enquire">
                            </a>
                        </div>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        $(function() {
            $('#ctl00_ContentPlaceHolder1_ShowListing_DataList1$3$0$enquire').click(function() {
                $('#enquireOverlay').fadeIn('fast', function() {
                    $('#box').animate({ 'top': '160px' }, 500);
                });
            });
            $('#boxclose').click(function() {
                $('#box').animate({ 'top': '-200px' }, 500, function() {
                    $('#enquireOverlay').fadeOut('fast');
                });
            });
        });
    </script>

回答1:

you should use live.

  $("#boxclose").live("click", function() {
                    $('#box').animate({ 'top': '-200px' }, 500, function() {
                        $('#enquireOverlay').fadeOut('fast');
                    });
                });


回答2:

Just don't use an ID, use that handy class they already have:

$('a.activator').click(function() {
    $('#enquireOverlay').fadeIn('fast', function() {
        $('#box').animate({ 'top': '160px' }, 500);
    });
});

Or even better with .delegate():

$(".DataWebControlStyle").delegate(".activator", "click", function() {
    $('#enquireOverlay').fadeIn('fast', function() {
        $('#box').animate({ 'top': '160px' }, 500);
    });
});

Either of these approaches would both slime down you code and allow you to move it to an external, cache-able file for the user.