简体   繁体   English

jQuery HTML元素动态添加事件处理程序?

[英]jQuery html elements dynamically, adding event handlers?

Ive spent several hours trying to resolve an issue with very limited experience with jQuery which is not helping me. 我花了几个小时来尝试解决jQuery经验非常有限的问题,但这对我没有帮助。

I am wanting to search a database for a list of results using a few input fields and then a submit button, when you click submit the values are passed to a .php script which returns the results and these are displayed in a table within a div container which works perfect. 我想使用一些输入字段在数据库中搜索结果列表,然后单击“提交”按钮,当您单击“提交”时,这些值将传递到返回结果的.php脚本中,并且这些结果将显示在div的表格中完美的容器。

Each record is then displayed in its own row within the table, with columns for different data. 然后,每个记录将显示在表中其自己的行中,并带有用于不同数据的列。

record number name town etc 记录编号名称城镇等

What i want is for the record number to be a click link of some kind, which when clicked, it then passes that value and does a different mysql request displaying that unique records data in more detail in a different div container. 我想要的是记录号是某种单击链接,当单击该链接时,它将传递该值并执行不同的mysql请求,以更详细的方式在不同的div容器中显示该唯一记录数据。 This is the part i cant get to work as i believe its something to do with BINDING, or the .ON which i dont really know anything or understand how it works, as my experience is very limited. 这是我无法使用的部分,因为我认为它与BINDING有关,或者我真的不了解任何内容或不了解其工作原理的.ON,因为我的经验非常有限。

I have provided some sample code which consists of two files, jQuery.php and db.php, db.php is just simulating a database lookup for now (crude i know), to make it easier to show my code and what i am trying to do. 我提供了一些示例代码,该示例代码由jQuery.php和db.php两个文件组成,db.php目前仅在模拟数据库查找(我知道是粗略的),以使显示代码和我正在尝试的内容更加容易去做。

if you run jQuery.php and either enter a town (sheffield,rotherham) followed by click "get data" you get a refined list of results, if you just click get data you get all the results, you will see each results as a 4 dig ID Number, what i want to happen here is when you click that number it then loads just that record in a different div container, but its not working due to the dynamic content as i have read but don't understand. 如果您运行jQuery.php并输入城镇(谢菲尔德,罗瑟汉姆),然后单击“获取数据”,则将获得精确的结果列表;如果您仅单击获取数据,则将得到所有结果,您将看到每个结果为4挖掘ID号,我想在这里发生的事情是,当您单击该号时,它只是将该记录加载到另一个div容器中,但是由于动态内容(如我已阅读但不理解)而无法使用。

You will see i have made an example of the reference number 1005 at the top of the page, and if you click on this, it loads that unique record fine, but i just can't get it to work with the ones in the table. 您会在页面顶部看到一个参考编号为1005的示例,如果单击该示例,它会很好地加载该唯一记录,但是我无法使其与表中的记录一起使用。

jquery.php jquery.php

    <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $(".click").click(function() {
            var recordid = $(this).attr("id");
            $('#2').load("db.php?id=" +recordid);
        });

        $("#get").click(function() {
            var town = $("#town").val();
            $('#1').load("db.php?town="+town
            );
        });
    });
</script>

OUTSIDE OF DYNAMIC HTML RECORD ID : - <a class = 'click' id = '1005'>1005</a><br>
<br>
Town <input type="textbox" id="town" ><br>
<button id="get">Get Data</button>
<br>


----<br>
*<div id="1" name='records_all'></div>
----<br>
*<div id="2" name='record_unique'></div>
----<br>

db.php ( crude code to simulate a db lookup, just for purpose of this problem ) db.php(用于模拟数据库查找的原始代码,仅用于解决此问题)

    <?php
$id = $_GET['id'];
$town = $_GET['town'];

echo "<pre>";

$data[]= array('id' => '1001', 'town' => 'sheffield', 'street' => 'national av', 'name' => 'neil');
$data[]= array('id' => '1002', 'town' => 'rotherham', 'street' => 'maple drive', 'name' => 'steve');
$data[]= array('id' => '1003', 'town' => 'leeds', 'street' => 'poplar drive', 'name' => 'john');
$data[]= array('id' => '1004', 'town' => 'rotherham', 'street' => 'exchange st', 'name' => 'claire');
$data[]= array('id' => '1005', 'town' => 'sheffield', 'street' => 'main street', 'name' => 'sarah');
$data[]= array('id' => '1006', 'town' => 'rotherham', 'street' => 'holderness rd', 'name' => 'jo');



if ($id) {
    foreach ((array)$data as $key => $value) {
        if ($data[$key]['id'] == $id) {
            echo $data[$key]['id']."<br>";
            echo $data[$key]['name']."<br>";
            echo $data[$key]['street']."<br>";
            echo $data[$key]['town']."<br>";
        }
    }
} else {
    if ($town) {
        foreach ((array)$data as $key => $value) {
            if ($data[$key]['town'] == $town) {
                $link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
                echo "{$link} {$data[$key]['town']}  {$data[$key]['name']}<br>";
            }
        }
    } else {
        foreach ((array)$data as $key => $value) {
                $link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
                echo "{$link} {$data[$key]['town']}  {$data[$key]['name']}<br>";
        }
    }
}

If the elements are not in the DOM at the time of their jQuery selection then the events will not be added with the way you wrote your code. 如果在选择jQuery时元素不在DOM中,那么事件将不会以您编写代码的方式添加。 However alternatively you can write your code like this 但是,您也可以这样编写代码

$(document).ready(function() {
    $(document).on('click', '.click', function() { //this is the only thing that changed
        var recordid = $(this).attr("id");
        $('#2').load("db.php?id=" +recordid);
    });

    $("#get").click(function() {
        var town = $("#town").val();
        $('#1').load("db.php?town="+town
        );
    });
});

This code should completely replace your javascript. 此代码应完全替代您的JavaScript。 It creates a live listener for all future elements in the document with the class click. 它通过单击class为文档中的所有将来元素创建一个实时侦听器。

You need to use event delegation to solve this issue. 您需要使用事件委托来解决此问题。 Look at the jQuery docs for .on here under the " Direct and delegated events " section 看看jQuery的文档的.on 这里的“ 直接和委托的事件 ”部分下

Try something like 尝试类似

$('#1').on('click', '.click', function() {
    var recordid = $(this).attr("id");
    $('#2').load("db.php?id=" +recordid);
});

This will work as long as the #1 element is in the DOM when the jQuery event bindings are run. 只要运行jQuery事件绑定时,只要#1元素位于DOM中,它就会起作用。 Essentially you're binding the click event to the #1 element instead of having to bind it to elements after loading them in. The jQuery docs do a good job of explaining this. 本质上,您是将click事件绑定到#1元素上,而不是将它们加载后必须绑定到元素上。jQuery文档在解释这一点方面做得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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