Javascript 如果元素id定义为php函数,如何编写jquery append$(“id”)append()语句?
我正在建立一个网站,一个网页包含相同的元素,元素id是由php函数创建的,因此元素id是唯一的。 我想使用jqueryappend语句添加id为php函数创建的div元素。如何编写jqueryappend语句 HTML部分:Javascript 如果元素id定义为php函数,如何编写jquery append$(“id”)append()语句?,javascript,php,jquery,html,mysql,Javascript,Php,Jquery,Html,Mysql,我正在建立一个网站,一个网页包含相同的元素,元素id是由php函数创建的,因此元素id是唯一的。 我想使用jqueryappend语句添加id为php函数创建的div元素。如何编写jqueryappend语句 HTML部分: <div id="q2s<?php the_ID(); ?>"> <span class="t2"><input type="text" class="t2" id="t2s<?php the_ID
<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>
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>
提前感谢。通过类似的方式,我通常会将代码/id/任何内容嵌入页面元素的数据属性中 HTML:
您所做的将起作用(虽然您最终会得到无效的重复id
属性,但这是一个单独的问题),但是您缺少id中的s
。var q2=$(“#q2”+getstarid)代码>-->var q2=$(“#q2s”+getstarid)代码>。我还建议您考虑使用公共类来对元素进行分组,因为动态生成/增量ID通常会成为维护的一大难题,通常需要使用级别来指出错误。此php代码实际上是wordpress插件文件的一部分,php函数_ID()是该插件的一部分。因此我必须使用_ID()为此。@RoryMcCrossan,还有什么是“无效的重复id属性”问题?这意味着您在DOM中只能有一个元素具有给定的id
属性。在您的代码中,看起来您正在使用id=“q2s”
@rorymcrossan创建多个元素,这会产生任何问题吗?这仍然会创建具有唯一id的元素吗?我的意思是,div id仅作为q2s提供,所以它会产生任何问题吗?@codewiz-否,如果上面的HTML位于某种PHP循环中,则不会创建唯一的元素。要做到这一点,您仍然需要返回到
<div id="q2s" data-id = "q2s<?php the_ID ?>">
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>');
});