gpt4 book ai didi

javascript - 如果元素 id 被定义为 php 函数,如何编写 jquery append $ ("#id").append() 语句?

转载 作者:行者123 更新时间:2023-11-29 18:58:10 24 4
gpt4 key购买 nike

我正在构建一个网站,并且网页包含具有元素 id 的相同元素,该元素由 php 函数创建,因此元素 id 是唯一的。我想使用jquery追加语句添加由php函数创建的带有id的div元素。如何编写jquery追加语句?

HTML 部分:

  <div id="q2s<?php the_ID(); ?>">          
<span class="t2"><input type="text" class="t2" id="t2s<?php the_ID(); ?>">
</span> <span id="star2s<?php the_ID(); ?>" class="rating2"></span>
<hr></div>

在html部分<?php the_ID();?>是用于获取唯一id的php函数

JAVASCRIPT 部分:

  <script>
var getstarid="<?php the_ID();?>";//php function for getting unique id
$(document).ready(function() {
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id="q2s<?php the_ID(); ?>"<span class="t2"><input
type="text" class="t2" id="t2s<?php the_ID(); ?>"></span> <span
id="star2s<?php the_ID(); ?>" class="rating2"></span><hr></div>');
});
</script>

在 javascript 部分 var getstarid="<?php the_ID();?>";用于获取唯一ID。

如何写var q2 = $("#q2"+getstarid);在 jquery 中,以便元素 id 可以更改,jquery 追加可以根据 php 函数值的变化进行工作 <?php the_ID();?>

提前感谢您。

最佳答案

对于这样的事情,我通常将代码/id/其他内容嵌入到页面元素的数据属性中。

HTML:

<div id="q2s" data-id = "q2s<?php the_ID ?>"> 

然后我使用 jquery“数据”方法在 JavaScript 中检索它:

JavaScript:

  var getstarid=$("#q2s").data("id");
...
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id='+getstarid+'><span class="t2"><input
type="text" class="t2" id="t2s"'+getstarid+'></span> <span
id="star2s'+getstarid+'>" class="rating2"></span><hr></div>');
});

这可能会给您带来两个好处: 1 - 更干净。您不应该将 PHP 代码与 JavaScript 混合在一起。 2 - 它可能会节省您一些数据库访问权限。不知道PHP是不是每次点击“”就去数据库。这样,它只调用该函数一次,然后让 jQuery 完成繁重的工作。

关于javascript - 如果元素 id 被定义为 php 函数,如何编写 jquery append $ ("#id").append() 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com