在页面加载时,是否可以将事件附加到DOM中不包含的元素?

时间:2015-05-26 19:20:53

标签: javascript jquery html dom

我有一张像

这样的表格
<table class="table-striped col-lg-12" id="resultsTable" >
    <thead>
        <tr>
            <th>
                Include? 
            </th>
            <th>
                Organization
            </th>
            <th>
                Category
            </th>
            <th>
                Orginal File Name 
            </th>
            <th>
                Link to File on Server
            </th>
            <th>

            </th>
        </tr>
    </thead>
    <tbody id="results">
        <tr>
        </tr>           
    </tbody>
</table>

tbody在用户触发特定事件后,button内的td内置$(function () { $('table button').click(function () { console.log("ok, it got clicked"); $('#file2Download').val($(this).closest('tr').find('td:first').text()); $(this).parents('form:first').submit(); }); }); 。我想是我的原因

td

不起作用是因为td在页面加载时不在DOM中。有没有一个很好的解决方法,或者我需要添加隐藏的public class myService { @Autowired ExecutorService executor; public Result getServiceResult(Token token, Profile profile){ //validate token and profile return getResult(token, profile).get(); } private getResult (Token token, Profile profile){ Future<Result> = threadPoolExecutor.submit( () -> myManager.createAccount(token, profile)); } } 或什么?

2 个答案:

答案 0 :(得分:0)

是的,您可以使用事件委派。

$("table").on("click","td",function(evt){ ...

答案 1 :(得分:0)

在某种程度上。它被称为事件委托。我们的想法是绑定到已存在的父元素,但要确保事件的实际目标与指定的选择器匹配。这是有效的,因为默认情况下事件一直向上传播到DOM的根元素。

使用jQuery的.on()代替.click,您可以轻松完成此操作:

$(function () {
    $('table').on('click', 'button', function () {
        console.log("ok, it got clicked");
        $('#file2Download').val($(this).closest('tr').find('td:first').text());
        $(this).parents('form:first').submit();
    });
});

要回答您提出的实际问题,不,您不能将事件附加到尚不存在的元素。