如何通过单击另一个类元素来获取类的当前html值

时间:2019-04-21 05:49:39

标签: javascript jquery

我从数据库中获取数据,在其中我想通过单击另一个最近的类来获取当前类的html值,并在另一个输入标签上显示它。

脚本

while($row = $query->fetch(PDO:: FETCH_ASSOC)) {
    $player= $row->['player'];
    $runs = $row->['runs'];
    $balss= $row->['balls'];

    $Name = "<strong class='player'> $player </strong>"; 
    $score = "<i class='runs'> $runs </i>";
    $balls= "<i class='balls'> $balls</i>";

    }

<div class="popup">
<input type="text" id="player" >
<input type="text" id="runs" >
<input type="text" id="balls" >
</div>


$(document).on('click', '.player', function(){
    $(".popup").toggle();
    var player = document.getElementsByClassName('player');
    for (var i = 0; i < player.length; i++)
    $("#player").val(player[i].html);

    var score = document.getElementsByClassName('runs');
    for (var i = 0; i < score.length; i++)
    $("#runs").val(score[i].html);
});

1 个答案:

答案 0 :(得分:0)

您可以简单地使用Jquery中的$(this).next()使其工作。

$(document).on('click', '.player', function(){
    var player = $(this).data('name');
    var runs = $(this).data('runs');
    $(".popup").show();
    $("#player").val(player);
    $("#runs").val(runs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<strong class='player' data-name='player1' data-runs='20'> player1 </strong>
<i class='runs'> 20 </i>
<br>
<strong class='player' data-name='player2' data-runs='30'> player2 </strong>
<i class='runs'> 30 </i>
<br>
<strong class='player' data-name='player3' data-runs='59'> player3 </strong>
<i class='runs'> 59 </i>
<br>
<strong class='player' data-name='player4' data-runs='46'> player4 </strong>
<i class='runs'> 46 </i>

<br>
<br>

<div class="popup" style="display:none">
<input type="text" id="player" >
<input type="text" id="runs" >
</div>

已编辑

我认为您可以使用data属性更好地处理这种情况。只需像下面那样更改您的PHP部分。

while($row = $query->fetch(PDO:: FETCH_ASSOC)) {
 $player= $row->['player'];
 $runs = $row->['runs'];
 $Name = "<strong class='player' data-name='$player' data-runs='$runs'> $player </strong>"; 
 $score = "<i class='runs'> $runs </i>";
}