如何在show函数中传递文本框值

how to pass text box value in show function?

本文关键字:文本 show 函数      更新时间:2023-09-26

我想在显示函数中传递文本框值

<div id="userComment">
    <input type="text" name="comment" id="comment" placeholder="Enter comment here">
    <button type="submit" class="postComment" onclick="show()" value="<?php echo $postId ?>">POST</button>
</div>

当您用jQuery标记问题时,您可以注册一个侦听器并将值传递给show。无需在元素上使用onclick进行设置。

$(function() {
    $(".postComment").click(function() {
        show($("#comment").val());
    });
});
function show(value) {
    console.log(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userComment">
  <input type="text" name="comment" id="comment" placeholder="Enter comment here">
  <button type="submit" class="postComment">POST</button>
</div>

我认为你可以这样写代码,这种方式非常简洁。

<div id="userComment">
    <input type="text" name="comment" id="comment" placeholder="Enter comment here">
    <button type="submit" class="postComment" onclick="show($('#comment').val())" value="<?php echo $postId ?>">POST</button>
</div>