簡體   English   中英

$(this).attr("data-id") 返回未定義

[英]$(this).attr("data-id") returning undefined

我正在建立一個網上商店,在每件商品上都有一個按鈕可以將該商品添加到購物車中。

<?php
$i = 0;
$path = "../images/women/winter/winter1";
$lang = "description_".get_param();

if(!$result = $db->query("SELECT * FROM cloths;")){
die("There was an error running the query [".$db->error."]");
}
while($winter = $result->fetch_assoc()){
    echo "<div class = \"boxsale $winter[image]\">
              <img src = \"$path.jpg\"/>
              <div class = \"test\"> $winter[$lang] </div>
              <select>
                <option>S</option>
                <option>M</option>
                <option>L</option>
                <option>XL</option>
                <option>XXL</option>
              </select>
              <button class = \"addToCart\" onclick = \"executeJS()\"> <i class = \"fa fa-shopping-cart\" data-id = \"$i\" aria-hidden=\"true\"></i></button>
      </div>";
      $i++;
  }?>

</div>

當您單擊按鈕時,最后幾行中的 executeJS() 會從單獨的文件中調用。

添加到購物車.js

function executeJS(){
  var id = $(this).attr("data-id");
  $.ajax( {
    type: "GET",
    url: "ajax.php?id=" + id + "&action=add"
  })
  .done(function(){
    alert("Product has been added.");
  });
}

我想從已單擊的按鈕中獲取數據 ID,

$(this).attr("data-id"); 但我得到的只是一個未定義為數據 ID 的標頭。

id=undefined&action=add

任何人都可以指出我正確的方向嗎?

謝謝

問題是因為$(this)沒有正確應用於您嘗試訪問的元素。 當使用基於 onclick 處理程序 ( onclick="test()" ) 的字符串時, this指的是窗口,而不是您嘗試訪問的元素。

 function test() { console.log(this.id); }
 <a href="#" id="test" onclick="test()" data-id="test">Link</a>

如果您想使用基於單擊符號的字符串,請顯式傳遞您的元素,然后執行$(element)

<button class = \"addToCart\" onclick = \"executeJS(this)\" data-id = \"$i\" />

Javascript:

function executeJS(element){
    var id = $(element).data('id');
    ...

就個人而言,一起跳過 attr-id,只需直接傳遞您的 id:

<button class = \"addToCart\" onclick = \"executeJS($id)\" />

看起來this可能指向窗口而不是按鈕。

您可以通過手動查找按鈕來解決此問題:

var id = $(".addToCart").attr("data-id");

只有當您只有一個按鈕時,這才真正起作用。 應該做的是使用 jquery 將事件附加到按鈕。

在你的 javascript 中:

$(".addToCart").click(function(e){
    var id = $(e.target).attr("data-id");
    $.ajax({
        type: "GET",
        url: "ajax.php?id=" + id + "&action=add"
    })
    .done(function(){
        alert("Product has been added.");
    });
})

e.target 指的是被點擊的按鈕。

使用常規函數function(){} )代替箭頭函數:

$(document).on("click",".deleteBtn",function(){
    //Your Code
});

由於您使用的是 jQuery,因此您應該這樣做。 首先,刪除 PHP 中的內聯事件處理程序(例如onclick = \\"executeJS()\\"

另一個問題是您的按鈕沒有 data 屬性,但它們的<i>子級有。

接下來,創建您的 jQuery 事件處理程序,綁定到按鈕。 通過這樣做,您可以使用$(this).find('i')來獲取 fontawesone <i>元素及其數據屬性.attr("data-id")

$('button.addToCart').click(function() {
  var id = $(this).find('i').attr("data-id");
  $.ajax({
      type: "GET",
      url: "ajax.php?id=" + id + "&action=add"
    })
    .done(function() {
      alert("Product has been added.");
    });
})

jsFiddle 示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM