2017-07-12 3 views
0

で親要素のパラメータに子要素の値を設定します。これで私の次のコード:私はの値を保持します。このようなボタンのonclickイベントを設定したいは動的にjavascriptの

<div class="w3-container" id="menuTopics"> 
      <button> 
      <a href="//somesite.com/someparam"> 
       <img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership 
      </a> 
     </button> 
     <button>.......</button> 
</div> 

href属性

<div class="w3-container" id="menuTopics"> 
      <button onclick="window.location.href='//somesite.com/someparam'"> 
      <a href="//somesite.com/someparam"> 
       <img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership 
      </a> 
     </button> 
     <button>.......</button> 
</div> 

hrefはURLの値を保持しているため、onclickイベントでも同じです。これは私の必要条件です。

以下は、私が書いたjavascriptです。

var getChilds = document.querySelectorAll("#menuTopics button"); 
     getChilds.forEach(function (item) { 
      item.setAttribute('onclick', 'location.href=""'); 

     }) 

は、しかし、私はタグからのhrefの値を取得する方法を知ってscroll down toパソコンへ転送します。

答えて

0

hrefの値を取得する必要があります。

var getChilds = document.querySelectorAll("#menuTopics button"); 
 
var href = document.getElementsByTagName('a')[0].href; 
 
getChilds.forEach(function(item) { 
 
    item.setAttribute('onclick', `location.href='${href}'`); 
 
}) 
 

 

 
var buttons = document.getElementsByTagName('button'); 
 

 
console.log('these are your buttons with on click events', ...buttons)
<div class="w3-container" id="menuTopics"> 
 
    <button> 
 
      <a href="//somesite.com/someparam"> 
 
       <img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership 
 
      </a> 
 
     </button> 
 
    <button>.......</button> 
 
</div>