【问题标题】:How can I print a button using a loop and have it perform a different function for each time it is printed?如何使用循环打印按钮并让它在每次打印时执行不同的功能?
【发布时间】:2020-06-16 02:41:37
【问题描述】:

我正在打印数据库中的数据。对于数据库中的每一行,都会打印一个包含该信息的新容器。每个容器都包含一个执行多读/少读功能的按钮。

我的问题是:第 2/3/4 个容器上的按钮正在更改第一个容器的文本,而不是它们自己的。我是否可以让每个按钮只更改它自己的容器文本。

'''

                    $sqls = "SELECT * FROM module_rating WHERE username='$name'";
                    $results = mysqli_query($conn, $sqls);
                    $queryResultss = mysqli_num_rows($results);
                    if ($queryResultss > 0) {
                        while ($row = mysqli_fetch_assoc($results)) {

                            echo "
                            <div class='wrapper'>

                            <div class='profileinfo'>

                             <h3>Module ".$row['Mod_Name']." </h3>
                            <h4> ".$row['Mod_Code']."</h4>
                            <h4> Your Rating </h4>
                            <p><b>Overall:</b> ".$row['Overall_rating']." Stars </p>
                            <p><b>Overall Comment:</b></br>
                            ".$row['Overall_comment']." </p>

                                <span id='dots'>...</span><span id='more'> <i class='fa fa-angle-right'></i>
                                <p>Workload: ".$row['Workload_rating']." Stars </p>
                            <p>Workload Comment: </p>
                                </span>

                            <button type='button' id='read' onclick='read()'> More</button>

JAVASCRIPT

    var i=1;
    function read() {

    if(!i){
    document.getElementById("more").style.display ="inline";

    document.getElementById("dots").style.display ="none";

    document.getElementById("read").innerHTML="Read Less";
    i=1;
    }
    else {
    document.getElementById("more").style.display ="none";

    document.getElementById("dots").style.display ="inline";

    document.getElementById("read").innerHTML="Read More";
    i=0;
    }
    }

【问题讨论】:

  • 这能回答你的问题吗? Getting the value of the input field using jquery
  • 不要重复 ID。使用具有上下文查找的类。副本将此作为答案。
  • 嗨,Taplar,我想这会有所帮助,谢谢。我明白了这个概念,我会尝试应用。

标签: javascript php html


【解决方案1】:

尝试在每个项目中包含一个 id

<span id='dots-". $row['id'] ."' >
<span id='more-". $row['id'] ."' >
<span id='read-". $row['id'] ."' >   

<button type='button' id='read' onclick='read(".$row['id'].")'> More</button>

并将 id 传递给 javascript 函数

function read(id) {...

【讨论】:

  • 评分 ID 是每条记录的唯一标识符。将 id 传递给 javascript 函数时 - 它应该是 'function read(RatingID) {...' 还是 - function read(".$row[RatingID].") {...?还。 'getElementById("more")' 现在会是 getElementById("more-".$row['RatingID]") 吗?
  • 如果您将 id 传递给 javascript 函数,您已经可以直接从函数 function read (id) { document.getElementById ("more-" + id); }
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多