2015-02-24 72 views
0

我通過查找元素來選擇要素a。我想通過它的名字來創建一個數組。檢索元素道具名稱並將其轉換爲數組

我想將其名稱除以-。我想這樣,但我得到錯誤的結果..

這將是這裏的正確方法是:

var name = $('a'); 
 

 

 
var names = name.map(function() { 
 
    return $(this).prop('name'); 
 
}); 
 

 
console.log(names.split('-')); // not getting result. getting error
<div> 
 
    <a href="#" id="one" name="one" >ONe</a> 
 
    <a href="#" id="two" name="two" >ONe</a> 
 
</div>

+0

不能陣列上使用.split();只有字符串。 – j08691 2015-02-24 14:45:34

+0

你想用連字符分隔*每個*名嗎?如果是這樣,結果應該是什麼樣子?假設我有'onename'和'two-name',我應該得到'[「onename」,「two」,「name」]還是'['onename',[「two」,「name」]]或者'[[「onename」],[「two」,「name」]]? – apsillers 2015-02-24 14:46:02

+0

你能準確的告訴我們你想要看到的內容嗎?另外,您應該使用'$ .fn.attr'來獲取名稱,而不是'.prop'。 – JAAulde 2015-02-24 14:49:14

回答

1

根據您的評論澄清,以下是你將如何使用jQuery和map功能來收集一套的name屬性從A元素的集合,並與-人物加入他們的行列:

$(function() { 
    var links = $('a'), 
     // names will be a jQuery collection because we're using `$.fn.map` 
     names = links.map(function() { 
      // using `.attr` instead of `.prop` 
      return $(this).attr('name'); 
     }); 

    // Because `names` is a jQuery collection, before we `join` them 
    // we have to get the array out of the collection using `get` 
    console.log(names.get().join('-')); 
}); 

Demo on Plunker

-1

變量names已經是這兩個值的對象。

您可以使用這些命令記錄主題。

console.log(names[0]); 
console.log(names[1]);