通过将每个特定元素与另一个属性值匹配来获取该属性值

时间:2016-08-07 13:37:41

标签: javascript jquery html

我正在尝试为我的产品创建一个愿望清单,我有一个与愿望清单产品的ID号相同的按钮,我希望当用户点击该按钮时,它会带来产品的数据名称值与ID号匹配。 这是我的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>

这是我的Javascript代码:

<script>
function myFunction() {
    var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");
    document.getElementById("show-fav").innerHTML = x;
}
</script>

我的代码只在点击任何按钮时显示名称apple。

任何帮助都会很感激。感谢

3 个答案:

答案 0 :(得分:1)

        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>

它只有苹果,因为在下面的代码中你使用的是[0]索引,这是苹果。

var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");

更新

使用以下功能:

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;
}

并将this添加到onClick中的函数参数。

<button onclick="myFunction(this)" data-id="1">Try it</button>

她是小提琴:https://jsfiddle.net/fs8L366m/

更新2:

    <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>

答案 1 :(得分:1)

我可以建议的一种方法是从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);
  }
});

&#13;
&#13;
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);
  }
});
&#13;
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;
}
&#13;
<!-- 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>
&#13;
&#13;
&#13;

参考文献:

答案 2 :(得分:0)

当然,因为你给你的变量x赋予属性data-name的值,即Apple。如果你想获得 Apple $ 1.22 ,你应该写:

var x = document.getElementsByClassName("add-to-cart")[0].innerHTML;
相关问题