动态创建<李>元素

Dynamically create <li> element on click

本文关键字:元素 gt lt 创建 动态      更新时间:2023-09-26

我在html 上有以下内容

<html>
<head>
    <script src="../3003_Testing/js/jquery/dist/jquery.js"></script>
    <script src="../3003_Testing/js/search.js"></script>
<title>Search Box</title>
    <link href="mycss.css" rel="stylesheet">
</head>
<body>
<section class="main">
     <form class="search" >
         <input id="searchAddress" type="text" name="q" placeholder="Search address" oninput="getAddress()" />
         <ul class="results" id="addressList">
         <li id="staticli"><a href="index.html">Static li element<br><span>This is a Static li element</span></a></li>
         </ul>   
     </form>
</section>
</body>
</html>

我正试图编写一个函数来处理单击任何列表元素时的事件。但当我点击<li>元素时,它似乎根本没有触发。

$('#addressList').on('click', 'li', function() {
    alert("clicked");
    alert( $(this).text() );
});

<li>元素是通过以下代码动态创建的:

listContents = $("<li id='"" + i + "'"><a href='"index.html'">" + addresses[i].lable + "</a></li>");
jQuery('#addressList').append(listContents);

我通过浏览器控制台验证了它们被正确创建为

outerHTML: "<li id="0"><a href="index.html">6 Cashew Crescent<br><span>6 Cashew Crescent. (S)679751</span></a></li>"

让我们先忽略动态列表。问题是,即使是我的静态列表元素在单击时也不会响应事件处理程序我已经想了几个小时了。。

我已经为我的静态li元素创建了一个jsfiddlehttps://jsfiddle.net/tmu50t9z/

jsfiddle到我的整个代码>https://jsfiddle.net/8wwnx64x/

$('#addressList li').on('click', function() {
    alert("clicked");
    alert( $(this).text() );
});

工作代码,尝试这个

HTML

<ul class="results" id='addressList'> </ul>
<button  id="aaa">Add LI</button>

JavaScript

var a=0;
$('#aaa').click(function() {
 $('#addressList').append('<li id="'+a+'"><a href="index.html">6 Cashew     Crescent<br><span>6 Cashew Crescent. (S)679751</span></a></li>');
 a++
});
$( "#addressList" ).on( "click", "li", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});