html中js循环创建id,javascript-如何获取动态创建的ID?

我绝对是使用javascript和ajax的初学者,所以这就是我现在坚持的原因.我有一个while循环,其中有2个不同的按钮.就像我想象的一样,两者都起作用,除了一件小事…

product-id始终仅传递给第一个元素,或者如果我将其更改为最后一个元素则传递.

如何将正确的产品ID传递给脚本?

这是我的PHP文件:

<?php while ( $product = $browse->fetch( PDO::FETCH_ASSOC ) ) :

$postid = $product[ 'id' ];

$userid = 1; ?>

我的Javascript是:

function add()

{

var userid = document.getElementById("userid").value;

var productid = document.getElementById("productid").value;

var collection = document.getElementById("collection").value;

var wishlist = document.getElementById("wish").value;

if(userid && productid && collection && wishlist) {

$.ajax

({

type: 'post',

url: 'post_collection.php',

data: {

user_id:userid,

product_id:productid,

collection_id:collection,

wishlist_id:wishlist

},

success: function (response) {

$("#content_"+ productid).load(" #reload_" + productid);

}

});

}

return false;

}

我知道示例中的产品ID始终相同,但是如果循环中有10个或更多条目,如何将正确的ID传递给脚本?

解决方法:

您的问题是id是唯一的,并且只能分配给一个元素一次,如下所示:

This is legal

This is illegal - It is no longer unique

This is legal

This is legal

您可以使用$(this)来访问当前单击的类,如下所示:

$('.paragraph').click(function() {

$(this).html('See, totally legal.');

});

您的解决方案需要向按钮添加onclick()方法.然后,将得到parent()表格.然后,您可以从类中获取find()并从表单数据中获取val().

您的表单也正在提交操作.您需要有一个< button>类型的按钮,因此它不提交操作.这也必须是一个类,因为如果您要多次创建它们,它将不是唯一的.

这是一个可以重新添加AJAX请求的有效示例.

$(document).ready(function() {

$('.submit-btn').click(function() {

var elements = {

'userid': $(this).parent().find('.userid').val(),

'productid': $(this).parent().find('.productid').val(),

'collection': $(this).parent().find('.collection').val(),

'wish': $(this).parent().find('.wish').val()

};

console.log("User ID: " + elements.userid);

console.log("Product ID: " + elements.productid);

console.log("Collection: " + elements.collection);

console.log("Wish: " + elements.wish);

// TODO: Add your AJAX request using these elements

});

});

button {

background: #0084ff;

border: none;

border-radius: 5px;

padding: 8px 14px;

font-size: 15px;

color: #fff;

cursor: pointer;

}

Add to collection

Add to collection

您的AJAX数据如下所示:

data: {

user_id: elements.userid,

product_id: elements.productid,

collection_id: elements.collection,

wishlist_id: elements.wish

}

您的PHP代码可能如下所示:

<?php foreach($browse->fetchAll(PDO::FETCH_ASSOC) as $product):

$id = $product['id'];

$productDd = $product['product_id'];

$productCategory = $product['category']; // TODO: change to your column nanme

$productWishList = $product['wish']; ?>

Add to collection

标签:ajax,html,javascript,php,jquery

来源: https://codeday.me/bug/20191108/2008340.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值