问题描述:

On clicking the button magic1 or magic2, the div mybox will be updated with a text, button id and button (different for magic1 and magic2).

After clicking on the newly generated button it should display the button id of the newly generated button in the box div. When I click on the newly generated button, box div is not getting updated. Here is the code.

jquerycode.php is the initial file. On clicking the button magic1 or magic2, Ajax will call the page session.php.

jquerycode.php file

<!doctype html>

<?php

$first=$_POST['q'];

echo $first;

?>

<html>

<head>

<meta charset="utf-8" />

<title>My jQuery Ajax test</title>

<style type="text/css">

#mybox {

width: 300px;

height: 250px;

border: 1px solid #999;

}

#box {

width: 300px;

height: 250px;

border: 1px solid #999;

position: absolute;

right:210px;

}

</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

$(".magic_button").click(function() {

var data = $(this).attr('id');

//alert (data);

$.ajax({

type: "POST",

url: "session.php",

data: { 'id': data }

}).done(function(msg) {

$("#mybox").html(msg);

});

});

});

</script>

<script>

$(".fir").click(function() {

var dataa = $(this).attr('id');

alert ("hello");

$.ajax({

type: "POST",

url: "jquerycode.php",

data: { 'q': dataa }

}).done(function(msg) {

$("#box").html(msg);

return false;

});

});

</script>

</head>

<body>

The following div will be updated after the call:<br />

<div id="mybox">

</div>

<div id="box">

</div>

<form name="magic">

<!-- <label for="name" id="name_label">Name</label>

<input type="text" name="name" id="name" size="30" value="" class="text-input" />

<label class="error" for="name" id="name_error">This field is required.</label> -->

<input type="button" class="magic_button" name="magic_button" id="magic_button_1" value="magic1" />

<input type="button" class="magic_button" name="magic_button" id="magic_button_2" value="magic2" />

</form>

</body>

</html>

session.php file

 <?php

$id = $_POST['id'];

$id = ucwords(implode(' ',explode('_',$id)));

if($id==="Magic Button 2")

{

echo "hey its button 2!!";

?>

<input type="button" name="butb" id="second" class="fir" value="second"/>

<?php

}

else

{

echo "hey its button 1!!";

?>

<input type="button" name="buta" id="first" class="fir" value="First"/>

<?php

}

echo $id;

?>

网友答案:

Best if you can use JQuery Live() for dynamic Generated Elements :

$("a.offsite").live("click", function(){ alert("Goodbye!"); });                // jQuery 1.3+

Beca JQuery Live() is deprecated you need to use JQuery on()

$("#elementid").on("click", function(event){
alert($(this).text());
});
相关阅读:
Top