javascript - jQuery/Ajax 在警报中正确发送 "data-"值,但无法将其附加到 php 中的特定 div 中

标签 javascript php ajax

我目前有一个 html 按钮,它的正下方有一个 div,我想在其中发布某些数据。

这两个元素都在 php for 循环中。

<?php for($i = 0 ; $i < 10; $i++){ ?>
    <div class="form-group">
          <label class="col-md-4 control-label" for="ver"></label>
              <div class="col-md-4">
                  <button data-dnipass="<?= $dni?>" class="ver" name="ver" class="btn btn-primary">
                      Ver líneas
                  </button>
              </div>
       </div>   
  <div id ="<?= $i?>" class="table userInfo" data-formpost="<?= $dni?>"></div> 
<? } ?>

$dni 是我从数据库中获取的值,并且对于每次迭代都是唯一的。

然后我有一个 ajax 脚本执行以下操作

$(document).ready(function(){
        $(".ver").click(function(event){
        var pulsado = $(this).data("dnipass"); //this is properly asigning the data
        alert(pulsado); //this properly launches an alert with my desired value
        $(this).data("formpost").append(pulsado); //im trying to append my variable to my ".userinfo" div but im unable to do so, since I dont know how to identify so
    });
    })

如何将 var pulsado 附加到类为“userinfo”的 div 中? var pulsado 的内容是一个简单的字符串,例如“x1234”或“x4321”......

最佳答案

试试下面的代码

    $(".ver").click(function(event){
        var pulsado = $(this).data("dnipass"); //this is properly asigning the data
        $(this).closest('.form-group').next('.userInfo').append(pulsado);
    });

closest 找到 div,您的 button 被包裹在该 div 下。 next 然后找到带有 userInfo 类的直接 div

关于javascript - jQuery/Ajax 在警报中正确发送 "data-"值,但无法将其附加到 php 中的特定 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58950137/

相关文章:

javascript - 如何防止JavaScript中的表单提交

javascript - 在递归中操作变量

php - 无法从我的 mysql 数据库中选择

javascript - 尝试通过 JQuery Ajax 将特殊字符发送到 PHP 脚本

javascript - 将 blob 响应视为 Angular 图像

当我从链接访问页面时,Javascript 第一次没有执行

php - Laravel 数据库不同字段之间的唯一键

php - 正则表达式在它们之间有空格时加入数字

javascript - 在 JQuery 中,为什么 ajax 请求之一有效,而其他请求无效?

javascript - jquery ajax - 查询参数的表单序列化问题