无法从动态PHP表单的Ajax/JSON响应修改/操作动态内容


Cannot Modify/Manipulate Dynamic Content From Ajax/JSON Response for A Dynamic PHP Form

我需要一个动态表单,它应该像这样工作:

  1. 当用户按下"添加"按钮时,会出现一个新的<。div>DOM来选择一个包
  2. 根据包的不同,行必须更改颜色(通过添加/删除某些类)

但我不能让它工作。这是我的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或变量方面没有问题(还好,当我提醒它时,会出现正确的值——但在我添加类之后,看不到颜色变化)。我运行它:

a。单击按钮,加载Ajax内容。

b。Ajax内容(其结果包含a)已成功加载。

c。失败:更改时,将类"package1"添加到div行。(所以,我在获得正确的id或类名方面没有问题。当我提醒变量时,它会给出正确的结果,但颜色不会改变。我无法检查类是否成功添加。)

$("#content").on("change", "select.switch", function (e) {
    e.preventDefault();
    $('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});

假设其他一切正常

//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');

这就是问题所在。要获得attibute id,你必须进行

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)。很抱歉,感谢您抽出时间:)