[英]Add dynamic id to a jquery selector
I am using a plugin named as Ladda which basically does is adds a loader when the button in clicked!我正在使用一个名为Ladda的插件,它基本上是在单击按钮时添加一个加载程序! I am populating a table from the database and adding these button in the last column of every row!我正在从数据库中填充一个表,并在每一行的最后一列中添加这些按钮! Here's my initial code这是我的初始代码
<?php
$query="select client_id,fullname,email,status
from atom_users ORDER BY id DESC";
$stmt = $db->prepare($query);
if($stmt){
$stmt->execute();
$stmt->bind_result($id,$fullname,$email,$status);
while ($stmt->fetch())
{
?>
<tr>
<td><?= $id?></td>
<td><?= $fullname?></td>
<td><?= $email?></td>
<td><?= str_replace("-"," ",$status)?></td>
<?= ($status=="archive" ? $status2='Un-Archive' : $status2="Archive");?>
<td>
<button class="ladda-button <?=$id?>" data-color="green" data-style="expand-left" onclick="val('<?= $id?>','<?= $status2?>')">
<?= $status2?>
</button>
</td>
</tr>
<?php }
$stmt->close();
} ?>
What am I doing here is fairly simple just outputting data and in this code there is button!我在这里做的是相当简单的只是输出数据,在这段代码中有按钮! Now for every button to be unique I've added an $id
variable to class of each button so that when loader is run on click of a button it runs on the button that is pressed.现在,为了让每个按钮都是唯一的,我在每个按钮的类中添加了一个$id
变量,以便在单击按钮时运行加载程序时,它会在按下的按钮上运行。 Now here's the function:现在这里的功能:
function val(id,status){
alert(id);
alert(status);
//original line
//var l = Ladda.create( document.querySelector( '.button-demo #btn' ) );
//dynamic
var l = Ladda.create( document.querySelector( '."'.+id+.'"' ) );
l.start();
}
Now the issue is straight forward the two lines现在的问题是直截了当的两条线
var l = Ladda.create( document.querySelector( '."'.+id+.'"' ) );
l.start();
are creating the loader now I want to add the id received in the function into the querySelector so that it works dynamically I have tried a lot but it is not accepting id!现在正在创建加载程序我想将函数中收到的 id 添加到 querySelector 中,以便它动态工作我已经尝试了很多,但它不接受 id! any recommendations?有什么建议吗?
As you had mentioned, your ID is a number.正如您所提到的,您的 ID 是一个数字。 While it's acceptable in HTML for ID's and classes to start with numbers, selectors will not work properly for these.虽然在 HTML 中 ID 和类以数字开头是可以接受的,但选择器将无法正常工作。
So, first, you can prefix your class so that it doesn't start with a number.因此,首先,您可以为类添加前缀,使其不以数字开头。 This will allow us to find it without having to do any crazy escaping with our selectors:这将使我们能够找到它,而不必对我们的选择器进行任何疯狂的转义:
<button class="ladda-button myClass_<?=$id?>" data-color="green" data-style="expand-left" onclick="val('<?= $id?>','<?= $status2?>')">
Now that our class is "findable", we can modify the querySelector
to find it properly:现在我们的类是“可查找的”,我们可以修改querySelector
以正确查找它:
var l = Ladda.create(document.querySelector(".myClass_"+id));
This should solve your issue.这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.