如何使文本区和提交按钮在.php文件隐藏在数据库中的每一行


How to make Textarea and submit button in .php file hide for every row in database?

一直在处理一些数据库数据调用到.php文件。这个php文件包含一个"添加"按钮,一个"文本区"和一个"提交"按钮。

我确实添加了一些J查询脚本,使"文本区和提交"按钮隐藏,直到"添加"按钮被点击,"文本区和提交"都隐藏,当"提交"按钮被点击,使"添加"按钮重新出现。

任何事情都工作得很好,但只有故障是,脚本只工作于表中的第一行,其余行不受影响。

我想我应该用一个循环之类的…我花了几个小时,但还是没能自己弄明白。

我的脚本如下:

<!DOCTYPE html>
<html lang="en">
<head>
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "the_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js">
</script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$().ready = function() {
 $('#text').hide();
    $('#textsubmit').hide();
    $("#addanswer").click(function() {
        $('#addanswer').hide();
        $('#text').fadeIn('slow').focus();
        $('#textsubmit').fadeIn('slow');
    });
    $('#text').blur(function(){
        $('#text').hide();
        $('#textsubmit').hide();
        $('#addanswer').fadeIn('slow');
    });
}();
});//]]> 
</script>
</head>
<body>
<?php 
      if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) { 
?>
<button class="addanswer" id="addanswer"><B>Add Answer</B></button>
<form name="answerswer" method="post" action="output.php">
<textarea type="text" class="text" name="text" required id="text" placeholder="Please type your question here.."></textarea>
<button type="submit" id="textsubmit" class="textsubmit"><B>Submit</B></button>
</form>
<?php     }
    } else {
echo "0 results";
        }
    $conn->close();
?>
</body>

由于同一个ID不能多次出现,您可以这样做:

<?php
foreach( $your_data as $index => $data ){
    echo '<button class="addanswer" id="addanswer_'.$index.'"><B>Add Answer</B></button>';
    echo '<form style="display:none;" name="answerswer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
    echo '<textarea style="display:none;"  type="text" class="text" name="text" required id="text_'.$index.'" placeholder="Please type your question here.."></textarea>';
    echo '<button style="display:none;" onClick="addanswer('.$index.');" type="submit" id="textsubmit_'.$index.'" class="textsubmit"><B>Submit</B></button>';
    echo '</form>';
}
... Other code stuff.

现在每一行都有一个不同的ID,因为我们使用了$index变量。同时我们也将$index传递给javascript函数。所以javascript可以根据$index的值做任何事情。

你可以有你的javascript函数,像这样

<script type='text/javascript'>
function addanswer(index){
    $('#addanswer_' + index).hide();
    $('#text_' + index).fadeIn('slow').focus();
    $('#textsubmit_' + index).fadeIn('slow');
}
</script>

注意:我没有通过运行来检查这段代码。我想你会对此有所了解的。

谢谢