在JavaScript中使用返回值作为变量


Using a return value as variable in JavaScript

我有一个JavaScript,它发送信息并将其返回给div。我工作得很好,但我想让div id变量取决于返回中的内容。例如:

function autoSubmit3() {
    $.post(
        'updatetype.php', 
        $('form[name="reportform"]').serialize(), 
        function (output) {
            $('#update').html(output).show();
        }
    );
}

将成为

function autoSubmit3() {
    $.post(
        'updatetype.php', 
        $('form[name="reportform"]').serialize(), 
        function (output) {
            $('#4update').html(output).show();
        }
    );
}

如果返回了"4:Type updated."。

目标div是

<div id="' . $Count . 'update"></div>

在"updatetype.php"页面上是

echo $Count, ": Type updated.";

如果我已经理解:

function autoSubmit3() {
    $.post(
        'updatetype.php', 
        $('form[name="reportform"]').serialize(), 
        function (output) {
            var id = parseInt(output); // or anything you want to get the number
            $('#' + id + 'update').html(output).show();
        }
    );
}

事实上,看看第n个孩子和情商,这可能会更容易。

这可能是您正在寻找的东西。(没有所有ajax的东西)

php

$array = array(1, 2, 3, 4);
foreach ($array as $index => $value) {
    echo '<div id="' . $index . '_item">' . $value . '</div>';
}

javascript

'use strict'
var index = 2; // get your index 
var id = '#' + index + '_item';
var element = $(id); // do your stuff with it

"我想让div id变量取决于返回中的内容"

您可以使用以下方法(使用JQuery)动态更改div的id:

$('#2update').attr('id',newNumber+'update');

这里的粗略示例