0

同様の「a」要素から受け取った配列があります。

links = jQuery('a');

href の宛先とコンテンツを含む文字列を取得するにはどうすればよいですか? 何かのようなもの:

<a href="/dest1">First</a>
<a href="/dest2">Second</a>
need =>
/dest1 First, /dest2 Second
4

4 に答える 4

2

あなたは使用することができmap()ますjoin()

$('a').map(function(index, link) {
    return link.href + ' ' + $(link).text();
 // return [link.href, $(link).text()].join(' ');  // This works too
}).get().join(', ');

デモ: http://jsfiddle.net/t4nr5/

  • .map()一致した要素を繰り返し処理します。
  • return要素を (オブジェクトで) 返された文字列に置き換えます。
  • .get()返された jQuery オブジェクトを基礎となる JS オブジェクト (この場合は配列) に変換します。
  • .join()パーツを結合します。
于 2013-01-19T20:57:32.470 に答える
1

これを行う方法を示す小さな jsFiddle を作成しました。ここで実際の動作を確認できます: http://jsfiddle.net/tUY5K/

これは、作業を行うメソッドです。

function anathem() {
  var links = $('a');
  var anathemString = "";
  links.each(function (index) {
    anathemString += $(this).attr('href') + " " + $(this).html();
    if (index != links.length - 1) {
      anathemString += ", ";
    }
  });
  return anathemString;
}
于 2013-01-19T21:07:41.793 に答える
0

これを試して:

    var hrefs_array = $.map($('a'), function(el) { return [$(el).attr("href"), $(el).text()];}) 

または、このようなもの

    var hrefs_array = [];
    $('a').each(function(index, el){
                     hrefs_array.push([$(el).attr("href"), $(el).text()]);
                });
于 2013-01-19T21:03:28.980 に答える
0

最初にリンクとコンテンツを取得するため。

var first_link = $('a:eq(0)').attr('href'); //first link
var first_content_text = $('a:eq(0)').text(); //content of first anchor element
var first_content_html = $('a:eq(0)').html(); //content of first anchor element including markup

2 番目のリンクとコンテンツを取得するには:

var second_link = $('a:eq(1)').attr('href'); //second link
var second_content_text = $('a:eq(1)').text(); //content of second anchor element
var second_content_html = $('a:eq(1)').html(); //content of second anchor element including markup

さまざまなテクニック:

":eq" 疑似クラス

$('a:eq(0)'); //this gets the first anchor. (":nth-child" pseudo-class is "0-indexed", meaning it starts counting from 0)

":nth-child" 疑似クラス

$("a:nth-child(1)"); //this also gets the first anchor. (":nth-child" pseudo-class is "1-indexed", meaning it starts counting from 1)

.first() および .next() メソッド

$("a").first(); //gets the first anchor element
$("a").first().next(); //gets the second anchor element

基になる DOM 要素を取得する

$('a').get(0); //This gets the first element in the anchor node list
$('a')[0]; //This also does the same but cannot specify a negative index
于 2013-01-19T20:57:25.157 に答える