我使用Viunal Studio 2015和IE浏览器进行调试
首先我点击超链接"AAA",跟踪调试进入函数'$("#HrefBtn_1"(。点击(函数(('成功
,然后ajax html响应"BBB"以分配给$('#formDefault_2'(
,然后我点击超链接"BBB",跟踪调试无法进入函数'$("#HrefBtn2"(。点击(函数(('
Default1.aspx=>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="js/jquery-2.1.4.min.js"></script>
<script>
$(function() {
$("#HrefBtn_1").click(function () {
$.ajax({
url: 'Default1.aspx/GetDataTest',
type: 'POST',
data: JSON.stringify(),
contentType: 'application/json; charset=UTF-8',
dataType: "json",
error: function (xhr) {
},
success: function (SuccessReturnVaule) {
var lsHTML;
lsHTML = "<a href='#' id='HrefBtn_2' rel='example'>BBB</a>";
$('#formDefault_2').html(lsHTML);
//$('#formDefault_2').append(lsHTML);
}
});
});
$("#HrefBtn_2").click(function () {
var lsTemp;
lsTemp = "Here!";
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="formDefault_1">
<a href="#" id="HrefBtn_1" rel="example">AAA</a>
</div>
<div id="formDefault_2">
</div>
</div>
</form>
</body>
</html>
Default1.aspx.cs=>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Collections;
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDataTest()
{
return "";
}
}
原因是在``中添加的超链接是动态添加的,因此您的click
功能将不起作用,您需要使用on()
:
$("#formDefault_2").on("click","#HrefBtn_2",function () {
var lsTemp = "Here!";
});
没有触发点击的原因是动态添加了元素#HrefBtn_2
。因此,您应该使用on
事件来绑定动态添加的dom的单击,或者您可以在元素渲染到html后绑定单击事件,如下所示。
我添加了一个函数bindButtonClick
,它将在html附加到页面后触发,该页面将绑定单击操作。
$(function() {
$("#HrefBtn_1").click(function () {
$.ajax({
url: 'Default1.aspx/GetDataTest',
type: 'POST',
data: JSON.stringify(),
contentType: 'application/json; charset=UTF-8',
dataType: "json",
error: function (xhr) {
},
success: function (SuccessReturnVaule) {
var lsHTML;
lsHTML = "<a href='#' id='HrefBtn_2' rel='example'>BBB</a>";
$('#formDefault_2').html(lsHTML);
//$('#formDefault_2').append(lsHTML);
bindButtonClick();
}
});
});
function bindButtonClick() {
$("#HrefBtn_2").click(function () {
var lsTemp;
lsTemp = "Here!";
});
}
});