0

I create a textarea and a button on a loop based on a certain condition:

while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here

<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}

Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.

I tried this, but it only gives me the text of the first textarea and button created:

function post_pm_comment(thidid, pm_id, path, pm,getter)
{
    var pm_text = document.getElementById("pm_text").value;
}

What should I do? Thank you

4

1 回答 1

3

您的代码正在输出无效的 DOM 结构,因为页面上的id必须是唯一的。您不能id在多个元素上使用相同的元素。完全删除这些id值,您不需要它们。

完成后,最小更改的答案是传递this给您的处理程序:

onClick="post_pm_comment(this)"

...然后在您的处理程序中,进行导航:

function post_pm_comment(postButton)
{
    var pm_text;
    var textarea = postButton.previousSibling;
    while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
        textarea = textarea.previousSibling;
    }
    if (textarea) {
        pm_text = textarea.value; // Or you may want .innerHTML instead
        // Do something with it
    }
}

实例| 资源

于 2013-10-20T13:48:45.520 回答