[英]Cannot Modify/Manipulate Dynamic Content From Ajax/JSON Response for A Dynamic PHP Form
我需要一个动态的表单,它应该像这样工作:
但是我无法正常工作。 这是我的HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
我的Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
我的PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS。 表单并非如此简单,但是为了使问题解决更加容易,我删除了细节。 但我似乎无法即时更改课程。 在这附近,我们有解决方案还是好的工作?
编辑1:对不起,我之前并没有明确表态。 我获取ID或变量没有问题(没关系,当我警告它时会显示正确的值-但添加类后,看不到颜色变化)。 我运行它:
一种。 单击按钮后,加载Ajax内容。
b。 Ajax内容(结果包含)已成功加载。
C。 失败:更改后,将类“ package1”添加到div行。 (因此,获取正确的ID或类名没有问题。当我警告变量给出正确的结果时,颜色不会改变。我无法检查类是否已成功添加。)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
假设其他一切都OK
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
这就是问题。 要获得礼节身份证,您必须做
var id = $(this).attr('id').substr(6);
您必须使用$(this)
而不是this
来使用所有jQuery功能。
下同
$(row).addClass('package1');
因此,完整代码:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
将类更改为id可解决问题(使用#row0而不是.row0)。 对不起,谢谢您的时间:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.