如何查找已设置动态 ID 的元素

How to find Elements which have been set with dynamic ids

我希望能在以下方面提供一些帮助。

我必须为卡片的每一行动态设置每个倒数计时器的 id,以便每个计时器都有一个唯一的 ID。我通过 $each 循环设置 ID,它工作正常并经过测试。

我正在尝试找到它,以便输出倒数计时器的值。

在我用 php 做之前。使用 SQL 结果行 id 是 id。

 $("#timer<?php echo $id; ?>").val(days + "d " + hours + "h "+ minutes + "m " + seconds + "s" ).css("color", "black");

计时器计数器显示如下所示。

<input id="timer<?php echo $id; ?>"  class="timer" type="text" name="" value="" disabled>

定时器计数器显示如下所示,因为定时器 ID 现在通过 $each 循环动态设置。

数组 id 用于计时器计数器 id。例如。 “计时器 3”

<input id="timer"  class="timer" type="text" name="" value="" disabled>

我在 class 中保留了这样的变量,因此您可以看到它有效 $('.timer')

$('.timer').val(days + "d " + hours + "h "+ minutes + "m " + seconds + "s" ).css("color", "black");

我的问题 我如何填写元素 $(xxxx).. 像这样 $("#",timer+id) # 需要在那里。

片段

在代码片段中,我将元素保留为 $('.timer'),因此您会看到它有效。

页面加载后,按启动计时器按钮启动计数器计时器。它会在启动计数器之前提醒计数器的 Id。

结束游戏

我希望每一行都有自己独特的倒数计时器

$(document).ready(function(){
  // simulates jason data result from Ajax
  var data = [

{ "id":"1", "name": "Mike" ,"surname": "Rynes" ,"expiredate": "2021/02/25 23:25:00"},
{ "id":"2", "name": "James" ,"surname": "Bond" ,"expiredate": "2021/02/26 23:25:00"},
{ "id":"3", "name": "Harry" ,"surname": "Potter" ,"expiredate": "2021/02/27 23:25:00"},
  
    ];
  
     $.each(data, function( i, person ) {
    
    
   var personDetailCloned = $('.card').first().clone().show();
      
   personDetailCloned.find('.id').text(person.id);
   personDetailCloned.find('.name').text(person.name);
   personDetailCloned.find('.surname').text(person.surname);
   personDetailCloned.find('.expiredate').val(person.expiredate);
      
      //Generate a random number to be used for timer id
       var timerid = Math.floor(Math.random() * 100);
               personDetailCloned.find('.timer').attr("id","timer"+person.id);
       
      $('.card-container').append(personDetailCloned);
    
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="album py-1">
  <div class="container bg-light">
    <div class="row py-2">
      <div class="col-md-3 card-container" >
        <div class="card mb-3 shadow-sm"  style="display:none;">
          <div class="hover-container">
         </div>
          <div class="card-body CarDetail">
           <p class="card-text font-weight-bold">ID:
                 <span class="id"></span>
            </p>
            <p class="card-text font-weight-bold">Name:
                   <span class="name"></span>
            </p>
            <p class="card-text font-weight-bold">Surname:  
                <span class=" surname"></span>
            </p>
            <div class="d-flex justify-content-between align-items-center">
              <p class="font-weight-bold ">Registration: 
                 <span class="font-weight-plain"></span>
                <span class="registration"></span> <span>Expires:
                
        <input  type="text" class="timer"  id="timer"  value=""> </span> 

         <input type="text" class="expiredate" value="">
              </p>  
              
                    
<script>

$(document).ready(function () {
$(document).on('click', '.card .starttimer-btn', function(event){

var expiredate = $(this).closest('.card').find('.expiredate').val();
var id = $(this).closest('.card').find('.timer').attr("id");

 
alert(id);


//alert(expiredate);

var countDownDate = new Date(expiredate).getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  //Output the result in an element with id="demo"
 $('.timer').val(days + "d " + hours + "h "+ minutes + "m " + seconds + "s" ).css("color", "black");


  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

});
});

</script>

</div>
 <p><button class="starttimer-btn" >Start Timer</button> </p>
 </div>
 </div>
</div>   
    </div>
  </div>

</div>

非常感谢任何帮助和建议,谢谢!

由于从 .attr("id") 检索到的 id 已经包含完整的 id,您可以使用:

$("#" + id).val(...

在您的 ID 前面添加“ID 选择器”(#)。

其他一切都没有改变。

$(document).ready(function() {
  // simulates jason data result from Ajax
  var data = [

    {
      "id": "1",
      "name": "Mike",
      "surname": "Rynes",
      "expiredate": "2021/02/25 23:25:00"
    },
    {
      "id": "2",
      "name": "James",
      "surname": "Bond",
      "expiredate": "2021/02/26 23:25:00"
    },
    {
      "id": "3",
      "name": "Harry",
      "surname": "Potter",
      "expiredate": "2021/02/27 23:25:00"
    },

  ];

  $.each(data, function(i, person) {


    var personDetailCloned = $('.card').first().clone().show();

    personDetailCloned.find('.id').text(person.id);
    personDetailCloned.find('.name').text(person.name);
    personDetailCloned.find('.surname').text(person.surname);
    personDetailCloned.find('.expiredate').val(person.expiredate);

    //Generate a random number to be used for timer id
    var timerid = Math.floor(Math.random() * 100);
    personDetailCloned.find('.timer').attr("id", "timer" + person.id);

    $('.card-container').append(personDetailCloned);

  });
});


$(document).ready(function() {
  $(document).on('click', '.card .starttimer-btn', function(event) {

    var expiredate = $(this).closest('.card').find('.expiredate').val();
    var id = $(this).closest('.card').find('.timer').attr("id");


    alert(id);


    //alert(expiredate);

    var countDownDate = new Date(expiredate).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // Get today's date and time
      var now = new Date().getTime();

      // Find the distance between now and the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      //Output the result in an element with id="demo"
      console.log(id, $('#' + id).length);
      
      $('#' + id).val(days + "d " + hours + "h " + minutes + "m " + seconds + "s").css("color", "black");


      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
      }
    }, 1000);

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="album py-1">
  <div class="container bg-light">
    <div class="row py-2">
      <div class="col-md-3 card-container">
        <div class="card mb-3 shadow-sm" style="display:none;">
          <div class="hover-container">
          </div>
          <div class="card-body CarDetail">
            <p class="card-text font-weight-bold">ID:
              <span class="id"></span>
            </p>
            <p class="card-text font-weight-bold">Name:
              <span class="name"></span>
            </p>
            <p class="card-text font-weight-bold">Surname:
              <span class=" surname"></span>
            </p>
            <div class="d-flex justify-content-between align-items-center">
              <p class="font-weight-bold ">Registration:
                <span class="font-weight-plain"></span>
                <span class="registration"></span>
                <span>Expires:
                    <input  type="text" class="timer"  id="timer"  value=""> 
                </span>
                <input type="text" class="expiredate" value="">
              </p>
            </div>
            <p><button class="starttimer-btn">Start Timer</button> </p>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>


虽然以上回答了您的问题,但如果不提醒您动态 ID 不是您的朋友 (tm),那将是我的疏忽。

您很少需要动态 ID(如果框架添加了它们,在某些情况下它们会这样做,那么您可以忽略它们)。

通过对您的代码进行两个小的更改,您可以摆脱动态 ID:

而不是

var id = ...

存储元素本身:

var timerOutput = $(this).closest('.card').find('.timer');

那你就可以直接引用了:

timerOutput.val(...

更新了代码段(仅更改了 2 行(并删除了 console.log))

$(document).ready(function() {
  // simulates jason data result from Ajax
  var data = [

    {
      "id": "1",
      "name": "Mike",
      "surname": "Rynes",
      "expiredate": "2021/02/25 23:25:00"
    },
    {
      "id": "2",
      "name": "James",
      "surname": "Bond",
      "expiredate": "2021/02/26 23:25:00"
    },
    {
      "id": "3",
      "name": "Harry",
      "surname": "Potter",
      "expiredate": "2021/02/27 23:25:00"
    },

  ];

  $.each(data, function(i, person) {


    var personDetailCloned = $('.card').first().clone().show();

    personDetailCloned.find('.id').text(person.id);
    personDetailCloned.find('.name').text(person.name);
    personDetailCloned.find('.surname').text(person.surname);
    personDetailCloned.find('.expiredate').val(person.expiredate);

    //Generate a random number to be used for timer id
    var timerid = Math.floor(Math.random() * 100);
    personDetailCloned.find('.timer').attr("id", "timer" + person.id);

    $('.card-container').append(personDetailCloned);

  });
});


$(document).ready(function() {
  $(document).on('click', '.card .starttimer-btn', function(event) {

    var expiredate = $(this).closest('.card').find('.expiredate').val();
    
    // get the element (jquery obj)
    var timerOutput = $(this).closest('.card').find('.timer');
    var countDownDate = new Date(expiredate).getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

      // Get today's date and time
      var now = new Date().getTime();

      // Find the distance between now and the count down date
      var distance = countDownDate - now;

      // Time calculations for days, hours, minutes and seconds
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);

      timerOutput.val(days + "d " + hours + "h " + minutes + "m " + seconds + "s").css("color", "black");


      // If the count down is finished, write some text
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
      }
    }, 1000);

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="album py-1">
  <div class="container bg-light">
    <div class="row py-2">
      <div class="col-md-3 card-container">
        <div class="card mb-3 shadow-sm" style="display:none;">
          <div class="hover-container">
          </div>
          <div class="card-body CarDetail">
            <p class="card-text font-weight-bold">ID:
              <span class="id"></span>
            </p>
            <p class="card-text font-weight-bold">Name:
              <span class="name"></span>
            </p>
            <p class="card-text font-weight-bold">Surname:
              <span class=" surname"></span>
            </p>
            <div class="d-flex justify-content-between align-items-center">
              <p class="font-weight-bold ">Registration:
                <span class="font-weight-plain"></span>
                <span class="registration"></span>
                <span>Expires:
                    <input  type="text" class="timer"  id="timer"  value=""> 
                </span>
                <input type="text" class="expiredate" value="">
              </p>
            </div>
            <p><button class="starttimer-btn">Start Timer</button> </p>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>