Jquery追加元素id未标识

jquery append element id is not identified

本文关键字:标识 id 元素 追加 Jquery      更新时间:2023-09-26

我正在尝试使用jquery动态添加一个文本区域到div。虽然基本代码可以工作,但我怀疑存在一些问题。这是因为当我尝试使用它的id返回textarea的宽度时,它返回一个null。这意味着没有正确设置id,因为可以在页面中看到文本区域。这是我的jquery代码的一部分

var form = $('<form/>',{"id" : "AnswerBox"}).appendTo($("#unanswered"));
$('<textarea/>').attr({
    "rows":5,
    "id" : "AnswerBoxArea",
    "name" : "answerswer"               
}).appendTo('form');

现在如果我输入alert

alert($("#AnswerBoxArea").width());

返回NULL,不明白为什么。任何帮助吗?

我认为问题不在于宽度的设置。似乎更多的是元素id的设置。如果我执行alert($("#AnswerBoxArea").attr(" id "))它会返回undefined

似乎什么都不起作用。我提供了详细的代码

$( document ).ready(function() {
$.ajax({
        url: "myteacher.php",
        dataType: "json",
        success: function(response){
                        console.log(response);
                      $("#unanswered").append("<p style='text-align:justify; border-radius: 5px; background-color:rgb(220,220,220); padding: 5px'>"+response.qtext+"</p>");
                            $("#unanswered").append('<form method = "POST" style = "padding:5px; margin:5px;" id="AnswerBox">');
                            $("#unanswered form").append('<textarea rows="5" id="AnswerBoxArea" name="answerswer">');
                            $("#unanswered form").append('<br><input type="submit" value="Answer" id="AnsTextQ">');

        },
        error : function(jqXHR, textStatus, errorThrown) {
                    alert(jqXHR.status+",  " + jqXHR.statusText+",  "+textStatus+",  "+errorThrown);
        }
    });
    $(".AnswerBoxArea").css("width", $("#AnsBoxDiv").width()-30);
    $(".AnswerBoxArea").css("max-width", $("#AnsBoxDiv").width()-30);
    alert($("#unanswered").attr("id"));
    alert($("#AnswerBoxArea").attr("id"));

});

是变量作用域的问题吗?id是本地的,不能访问?

您是否尝试过css以获取/设置宽度?

Use jQuery's css method like this:
.css("width", width)
or this, if you plan on setting more attributes:
.css({"width":width})