简体   繁体   English

DOM 选择器在 Vanilla JavaScript 中给出 null 但在 jquery 中工作

[英]DOM selector giving null in Vanilla JavaScript but working in jquery

I am selecting an id using vanilla JS but ("qty").value;我正在使用 vanilla JS 选择一个 id,但是 ("qty").value; is giving me null answer but using the same code through jQuery is working fine after else my jQuery code line给我空答案,但通过 jQuery 使用相同的代码在我的 jQuery 代码行之后工作正常

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    var qty = jQuery("#qty").val();
  }

  var ajax = new XMLHttpRequest();
  ajax.open("post", "manage_cart.php", true);
  ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // Response
      var response = this.responseText;
      if (type == 'update' || type == 'remove') {
        window.location.href = 'cart.php';
      }
      document.querySelector('.cart-a span').innerHTML = response;
    }
  };
  
  var data = new URLSearchParams({
    pid,
    qty,
    type
  });
  ajax.send(data);
}

This is my vanilla JS code这是我的香草 JS 代码

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    var qty = document.getElementById('qty').value;
  }
  
  var ajax = new XMLHttpRequest();
  ajax.open("post", "manage_cart.php", true);
  ajax.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // Response
      var response = this.responseText;
      if (type == 'update' || type == 'remove') {
        window.location.href = 'cart.php';
      }
      document.querySelector('.cart-a span').innerHTML = response;
    }
  };
  
  var data = new URLSearchParams({
    pid,
    qty,
    type
  });
  ajax.send(data);
}

My html and php code looks like this in which the id is different for each product but remove does need pid in the selector.我的 html 和 php 代码看起来像这样,其中每个产品的 id 不同,但 remove 确实需要选择器中的 pid。

 <div class="basket-product-c">
      <?php
                                        if(isset($_SESSION['cart'])){
                                            foreach($_SESSION['cart'] as $key=>$val){
                                            $productArr=get_product($con,'','',$key);
                $price=$productArr[0]['price'];
                $qty=$val['qty'];
    ?>
        <div class="price-c"><?php echo $price?></div>
        <div class="quantity-c">
          <input type="number" class="quantity-field-c" id="<?php echo $key?>qty" value="<?php echo $qty?>"/>
          <br/><a href="javascript:void(0)" onclick="manage_cart('<?php echo $key?>','update')">update</a>
        </div>
        <div class="subtotal-c"><?php echo $qty*$price?></div>
        <div class="remove-c">
        <a href="javascript:void(0)" onclick="manage_cart('<?php echo $key?>','remove')">Remove</a>
        </div>
      
        <?php } } ?>

If you log var qty to the console, are you getting null, or is it picking up the element?如果您将 var qty记录到控制台,您得到的是空值,还是获取元素? The only reason I can think of as to why the vanilla js version is not working, is that the jquery id selector fires slower than a getElementById().我能想到的为什么 vanilla js 版本不起作用的唯一原因是 jquery id 选择器比 getElementById() 触发得慢。 Ideally, there would be no difference, since jquery('#element') uses document.getElementById() under the hood.理想情况下,不会有什么区别,因为 jquery('#element') 在幕后使用 document.getElementById()。

Maybe do as @Elikill58 suggested and delay the selection by wrapping that line in a setTimeout() function.也许按照@Elikill58 的建议去做,并通过将该行包装在 setTimeout() 函数中来延迟选择。

Also, getElementById().value will return undefined if there's no value attribute, or blank if there is a value attribute present for that tag, but there is no value set.此外,如果没有 value 属性, getElementById().value 将返回 undefined ,如果该标签存在 value 属性,但没有设置值,则返回空白。

If the element is not being picked up at all by the selector, you'll get null as a response.如果选择器根本没有选择该元素,您将获得 null 作为响应。

Try this and see if it works:试试这个,看看它是否有效:

function manage_cart(pid, type) {
  if (type == 'update') {
    var qty = document.getElementById(pid + "qty").value;
  } else {
    setTimeout(() => {
      var qty = document.getElementById('qty').value;
    }, 200)
  }

You can play around with the delay timing to find one which is ideal for you.您可以调整延迟时间以找到最适合您的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM