【问题标题】:Classic ASP code injected buttons not firing jQuery click events经典的 ASP 代码注入按钮不触发 jQuery 点击事件
【发布时间】:2017-09-13 21:07:44
【问题描述】:

我正在使用两个经典的 asp 页面和一个 jquery .js 文件。现在,我的主 asp 页面在标记中包含一个插入按钮和一个包含经典 asp 标记的占位符 Div,带有两个按钮,已从第二个 asp 页面的内容动态注入其中。主 asp 页面引用了应用程序的外部 jquery 文件。我遇到的问题是主asp页面上的按钮触发了一个jquery按钮点击功能只是find;但是,第二页的注入代码中包含的两个按钮不会触发它们的 jquery 点击事件。

主 asp 默认页面代码(提交按钮和 jquery 工作正常):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Customer CRUD</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="scripts/jquery-1.11.2.js"></script>
    <script type="text/javascript" src="scripts/regras.js"></script>
    <script lang="javascript" type="text/javascript" ></script>
</head>
<body>
    <center>
        <h1>View Company</h1>   
        <hr/>       
        <div id="InjectionPlaceholder"></div>
        <hr/>
    </center>
    <div id="box" >
        <br/>
         &nbsp; Name: <input type="text" id="ContactName1" />
        <hr/>
         &nbsp;&nbsp;Address: <input type="text" id="address1" />
        <hr/>
        <button id="submit">Submit</button>
        <br/>
    </div>
    <center><div id="ErrorMsg"></div></center>
</body>
</html>

用于代码注入的第二个 asp 页面,它是经典的 asp 功能(它的两个按钮不会触发 jquery 事件):

<%        
    '' This page gets injected into the main Default asp page. On the page are also the Delete and Update asp calls
    Dim CustomerID
    <%
    ''======================================================
    '' The database is called to build the customer table used for injection 
    '' Buttons don't call the jquery functions.
    ''======================================================    
    Set rs = Server.CreateObject("ADODB.RecordSet")
    sql = "SELECT * FROM customers"
    rs.Open sql, bco 
    If not rs.eof then
    %><table border="1">
    <%
    Do while not rs.eof
    CustomerID = rs("CustomerID")
    %>                       
    <tr>
    <td>Company Name:<span id="CompanyName1"> <%=rs("CompanyName")%></span></td>    
    <td>align='center'>Contact Name: <span id='ContactName1'><%=rs("ContactName")%></span></td>
    <td>Address: <%=rs("Address")%></td>
     <td><button id="Update" onclick="updateClick(<%=CustomerID%>)">Update</button></td>
    <td><button id="Delete" onclick="deleteClick(<%=CustomerID%>)">Remove</button></td>
    </tr>              
    <%
    rs.movenext
    loop
    %>
    </table>
    <%
    Else
    Response.Write("No Records Found.")
    End If
    rs.Close
    Set rs = Nothing
    %>

外部jquery文件的内容:

    $(function () {
        console.log('Company JavaScript!');
        //SELECT
        try {
            GetCustomers();
        } catch (e) {
            console.log(e);
        }

        // This Button event is the one that works. It calls the insertClick event.
        $("#submit").click(insertClick);

        // This is the function that injects the markup from the Injection.asp 
        // into the Default.asp page. It is called in each button click event.
        //SELECT
        function GetCustomers() {

            $.post('Injection.asp', function (data) {
                $("#InjectionPlaceholder").html(data);

            });   
        };

        //This is one of the injected page click event that does not work. It's 
        //button is in the injected code
        function deleteClick(CompanyName) {
            alert("Test1"); //Alert doesn't get called
            //DELETE
            try {
                console.log('Remove Company =' + CompanyName);
                $.post('Injection.asp?delete=' + CompanyName);
                Refresh = false;
                GetCustomers();
                window.location.replace("http://localhost:82/Refresh.asp");

            } catch (e) {
                console.log(e);
            }
        }

        // This function works correctly. It's button is in the Default.asp 
        // page.
        function insertClick() {    
        //INSERT
            try {
                var nameIns = $("#ContactName1").val();
                var addressIns = $("#Address1").val();
                if (nameIns !== "" && addressIns !== "") {
                    $.post("Injection.asp.asp?ContactName" + nameIns + "&Address=" + addressIns);
                    $.post('Injection.asp', function (data) {
                        Refresh = false;
                        GetCustomers();
                        $("#CustomerName1").val("");
                        $("#Address1").val("");                     window.location.replace("http://localhost:82/Refresh.asp");
                    });
                } else {
                    alert("Insert Failed");
                }   

            } catch (e) {
                console.log(e);
            }
        }

        //This is one of the injected page click event that does not work. It's 
        //button is in the injected code
        //UPDATE
        function updateClick(company) {
            var nameUpd;
            var addressUpd;
            alert("Test2"); //Alert doesn't get called
            nameUpd = prompt("Enter the contact name:", "");
            addressUpd = prompt("Enter the contact address: ", "");

            if ((nameUpd === "" || nameUpd === null) && (addressUpd === "" || addressUpd === null)) {
                alert("Invalid input");

            } else {
                try {
                    console.log("Name: " + nameUpd + ", address: " + addressUpd + ", company: " + company);

                    var pageUpd = 'Injection.asp?CompanyName=' + company + '&ContactName=' + nameUpd + '&Address=' + addressUpd;
                    $.post(pageUpd, function (data) {
                        console.log(pageUpd);
                        Refresh = false;
                        GetCustomers();
                    window.location.replace("http://localhost:82/Refresh.asp");
                    });

                } catch (e) {
                    console.log(e);
                }    
            };    
        };   
    });

【问题讨论】:

  • JavaScript 不知道服务器端代码。生成的 HTML 是什么?只显示产生问题的代码。
  • 而不是像 onclick="updateClick()"> 这样分配 JS 函数,你应该这样做 $(document).on("click","#Delete",函数(){updateClick();});由于内容是动态加载的,因此不会触发。

标签: jquery


【解决方案1】:

快速浏览一下,这里有几个问题。具体有两个严重错误:

首先,这不会如你所愿:

onclick="updateClick()"

因为updateClick 函数在窗口的全局范围内不存在。因此,您很可能会在浏览器的开发控制台上遇到错误,该错误会准确地告诉您这一点。而是使用您已经使用的事件绑定。例如,看看你如何绑定这个:

$("#submit").click(insertClick);

这就是在 jQuery 中绑定事件的方式。因此,也可以将其用于您的其他活动。例如:

$("#Update").click(updateClick);

或者,如果在初始jQuery代码执行之后插入元素,使用事件委托:

$(document).on("click", "#Update", updateClick);

然而,这里的第二个问题是您在页面中重复使用id 值。这是无效的 HTML,因此 JavaScript 行为将是未定义的。具体来说,基于id 的选择器不会知道您要识别的哪个 元素。相反,使用一个类并绑定到所有元素:

<button class="update">Update</button>

和:

$(".update").click(updateClick);

$(document).on("click", ".update", updateClick);

一旦这些错误得到修复,您应该有一个有效的点击事件。但是,现在您还需要将 &lt;%=CustomerID%&gt; 值传递给这些事件。与其将其作为函数参数传递,不如将其设置为元素的数据属性,以便处理程序可以从单击的元素中动态获取它。像这样的:

<button class="update" data-customerID="<%=CustomerID%>">Update</button>

然后在处理函数中你可以得到那个值:

function updateClick() {
    var company = $(this).data('customerID');
    // the rest of your code...
}

【讨论】:

    【解决方案2】:

    当元素动态添加到 DOM 时,jQuery 无法将事件处理程序附加到它们。另一种方法是将事件处理程序附加到父元素 “静态”呈现给 DOM(如果没有这样的父元素,则呈现给文档)并传递子元素。

    示例:

    $('#click1').click(function(e){
      var child = '<div id="child">Child, click me</div>';
      $('#root').append(child);
    });
    
    $('#root').on('click','#child', function(e){
      console.log('child clicked');
    });
    
    /* this wont work!
    $('#child').click(function(e){
      console.log('child clicked');
    });
    */
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="root">
      <div id="click1">Add element</div>
      
    </div>

    【讨论】:

    • 如果我理解正确的话,它们确实会通过 js GetCustomers 方法动态插入(ajax)
    • 你说得对,我错过了。呈现的代码似乎有几个问题。
    • 看起来是的。您确实提到了其中的大多数,但是对于 OP 提到的具体问题,我认为这是添加的动态元素
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2015-08-28
    • 2019-06-22
    • 2016-07-01
    • 1970-01-01
    • 2011-11-19
    相关资源
    最近更新 更多