[英]Get attribute value for each specific element by matching it to another attribute value
I am trying to create a wish list for my products, I have a button with the same ID number of the product for wish list and I want when the user clicks on the button, it brings the data name value of the product that match with the ID number. 我正在尝试为我的产品创建一个愿望清单,我有一个按钮,该按钮具有与该愿望清单产品相同的ID号,并且我希望当用户单击该按钮时,它带来与之匹配的产品的数据名称值ID号。 this is my HTML :
这是我的HTML:
<html>
<div>
<ul>
<li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22" >Apple $1.22</a><button onclick="myFunction()" data-id="1">Try it</button></li>
<li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a><button onclick="myFunction()" data-id="2">Try it</button></li>
<li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a><button onclick="myFunction()" data-id="3">Try it</button></li>
<li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a><button onclick="myFunction()" data-id="4">Try it</button></li>
</ul>
</div>
<html>
this is my Javascript code: 这是我的Javascript代码:
<script>
function myFunction() {
var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");
document.getElementById("show-fav").innerHTML = x;
}
</script>
my code only brings the name apple when clicking any of the buttons. 我的代码仅在单击任何按钮时才使用苹果这个名字。
any help will be appreciate it. 任何帮助将不胜感激。 thanks
谢谢
var wishlist = Array(10); $(document).ready(function(){ //wishlist = JSON.parse($.cookie('wishlist') || '{}'); wishlist = JSON.parse(localStorage.getItem("wishlist") || '{}'); if(wishlist != null){ $.each(wishlist, function(index, name){ $('#wishlist').append($('<li>').val(index).text(name)); }); } else wishlist = {}; }); function myFunction(selectedElement) { var data_id = selectedElement.getAttribute("data-id"); var data_name = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name'); if(!wishlist.hasOwnProperty(data_id)){ wishlist[data_id] = data_name; $('#wishlist').append($('<li>').val(data_id).text(data_name)); //$.cookie('wishlist', JSON.stringify(wishlist)); localStorage.setItem("wishlist",JSON.stringify(wishlist)); //document.cookie = (wishlist); console.log($.cookie('wishlist')); console.log(wishlist); } else{ $('#wishlist li[value *= '+data_id+']').remove(); delete wishlist[data_id]; localStorage.setItem("wishlist",JSON.stringify(wishlist)); } //alert('Element already present'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <html> <div> <ul> <li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22" >Apple $1.22</a><button onclick="myFunction(this)" data-id="1">Try it</button></li> <li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a><button onclick="myFunction(this)" data-id="2">Try it</button></li> <li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a><button onclick="myFunction(this)" data-id="3">Try it</button></li> <li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a><button onclick="myFunction(this)" data-id="4">Try it</button></li> </ul> </div> <ul id="wishlist"> </ul> <html>
It is getting only apple because in following code you are using [0]
index which is apple. 它只得到苹果,因为在以下代码中您使用的是
[0]
索引,即苹果。
var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");
Use following function: 使用以下功能:
function myFunction(callingElement) {
var data_id = $(callingElement).attr('data-id');
var x = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name');
alert(x);
document.getElementById("show-fav").innerHTML = x;
}
and add this
to your function argument in onClick
. 并添加
this
在你的函数参数onClick
。
<button onclick="myFunction(this)" data-id="1">Try it</button>
Hers's the fiddle: https://jsfiddle.net/fs8L366m/ 她的小提琴: https : //jsfiddle.net/fs8L366m/
<script>
var wishlist = Array(10);
$(document).ready(function(){
//wishlist = JSON.parse($.cookie('wishlist') || '{}');
wishlist = JSON.parse(localStorage.getItem("wishlist") || '{}');
if(wishlist != null){
$.each(wishlist, function(index, name){
$('#wishlist').append($('<li>').val(index).text(name));
});
}
else
wishlist = {};
});
function myFunction(selectedElement) {
var data_id = selectedElement.getAttribute("data-id");
var data_name = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name');
if(!wishlist.hasOwnProperty(data_id)){
wishlist[data_id] = data_name;
$('#wishlist').append($('<li>').val(data_id).text(data_name));
//$.cookie('wishlist', JSON.stringify(wishlist));
localStorage.setItem("wishlist",JSON.stringify(wishlist));
//document.cookie = (wishlist);
console.log($.cookie('wishlist'));
console.log(wishlist);
}
else{
$('#wishlist li[value *= '+data_id+']').remove();
delete wishlist[data_id];
localStorage.setItem("wishlist",JSON.stringify(wishlist));
}
//alert('Element already present');
}
</script>
One approach I could suggest is the following, which removes the inline-event handlers ( onclick
, etc) from the HTML in favour of unobtrusive JavaScript: 我可以建议的一种方法是以下方法,该方法从HTML中删除了内联事件处理程序(
onclick
等),而采用了简洁的JavaScript:
// retrieving the <ul> element that contains the <a>
// and <button> elements:
var priceList = document.getElementById('priceList');
// binding the anonymous function of the
// EventTarget.addEventListener() method to handle
// the 'click' events on the <ul>:
priceList.addEventListener('click', function(e) {
// 'e' is the event object itself, passed in from
// addEventListener().
// caching the variables within the function:
var list = this,
// e.target is the element on which the
// listened-for event was originally fired:
clicked = e.target,
// here we create an <li> element:
li = document.createElement('li'),
// declaring, but not initialising, a
// a variable for later use:
desired;
// here we check if the originally-clicked element
// is a <button>, comparing the tagName of the clicked
// element - converted to lowercase - with the
// string of 'button':
if (clicked.tagName.toLowerCase() === 'button') {
// if a <button> was clicked then we prevent
// the default action of that <button>:
e.preventDefault();
// and look within the <ul> (cached as 'list')
// using the querySelector() method to find the
// first instance of an element, if any, matching
// the supplied selector, the selector here
// searches for an <a> element, with a 'data-id'
// attribute with the same attribute-value as held
// in the clicked element (here we use the
// HTMLElement.dataset API to retrieve that value):
desired = list.querySelector('a[data-id="' + clicked.dataset.id + '"]');
// we set the text-content of the created <li>
// to be equal to that held within the data-name
// attribute of the element stored in the
// 'desired' variable:
li.textContent = desired.dataset.name;
// here we simply append the created <li> element
// to the wishList <ul> element; obviously your
// own output is likely to be different so adjust
// to taste as required:
document.getElementById('wishList').appendChild(li);
}
});
var priceList = document.getElementById('priceList'); priceList.addEventListener('click', function(e) { var list = this, clicked = e.target, li = document.createElement('li'), desired; if (clicked.tagName.toLowerCase() === 'button') { e.preventDefault(); desired = list.querySelector('a[data-id="' + clicked.dataset.id + '"]'); li.textContent = desired.dataset.name; document.getElementById('wishList').appendChild(li); } });
li { list-style-type: none; width: 50%; clear: both; margin: 0 0 0.5em 0; padding: 0 0 0.2em 0; border-bottom: 2px solid #aaa; } a:link, a:visited { text-decoration: none; } a:hover, a:active, a:focus { text-decoration: underline; } a + button { float: right; padding: 0 1em; }
<!-- Note the addition of an id attribute ('priceList') to the <ul> element, in order to easily target it via JavaScript; also the removal of all inline event-handlers in order to use unobtrusive JavaScript and minimal repetition --> <div> <ul id="priceList"> <li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22">Apple $1.22</a> <button data-id="1">Try it</button> </li> <li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a> <button data-id="2">Try it</button> </li> <li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a> <button data-id="3">Try it</button> </li> <li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a> <button data-id="4">Try it</button> </li> </ul> </div> <!-- this element was added purely because you don't clearly state where it is that you want the 'names' to be 'brought' in your question; and this seemed as good an idea as any other I could think of to display them --> <ul id="wishList"></ul>
References: 参考文献:
document.createElement()
. document.createElement()
。 document.getElementById()
. document.getElementById()
。 document.querySelector()
. document.querySelector()
。 Element.tagName
. Element.tagName
Event.preventDefault()
. Event.preventDefault()
。 Event.target
. Event.target
。 EventTarget.addEventListener()
. EventTarget.addEventListener()
。 HTMLElement.datalist
. HTMLElement.datalist
。 Node.appendChild()
. Node.appendChild()
。 Node.textContent
. Node.textContent
。 String.prototype.toLowerCase()
. String.prototype.toLowerCase()
。 Of course, because you give to your variable x the value of the attribute data-name, which is Apple. 当然,因为您为变量x赋予了属性data-name的值,即Apple。 If you want to obtain Apple $1.22 , you should write :
如果要获得Apple $ 1.22 ,应输入:
var x = document.getElementsByClassName("add-to-cart")[0].innerHTML;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.