0

次のようなli要素があります。

<ol id="selectbox">
    <li class="boxes" name="bears">bees</li>
    <li class="boxes" name="cakes">candles</li>
    <li class="boxes" name="wine">beer</li>
    <li class="boxes" name="spoon">fork</li>
    <li class="boxes" name="bench">chair</li>
    <li class="boxes" name="matches">fire</li>
    <li class="boxes" name="kindling">wood</li>
</ol>

クリックすると、「bears」という名前を取得するか、「bees」というテキストを変数に入れたいと思います (両方を実行する方法を知っておくと役立ちます)。jQueryセレクターでこれを行うにはどうすればよいですか? 私は多くのことを試しました

var $radios = $('input[name="mybuttons"]');
$('#selectbox li').click(function(){
  var $btn = $(this).addClass('active');
  var idx = $btn.index();    
  var name = $('li['+idx+']').name();
});

var name = $('#li.active').name()

var name = $radios.eq(idx).prop('name')

4

4 に答える 4

2

.text()を使用してテキストを取得します

$(this).text()

および.attr('name')で名前を取得します

$(this).attr('name')

フィドル

于 2013-01-09T23:55:53.463 に答える
1

上手、

 $('#selectbox .boxes')

#selectbox内にクラスボックスを持つすべての要素の配列を返しますjQueryを使用して作業を楽にすることで、これを行うことができます

$('#selectbox .boxes').click(function(){
  var tmp_name = $(this).attr('name');
  alert(tmp_name);
  alert($(this).text()); // bees
  alert($(this).html()); // bees
  // changes the attribute name of this li element which has class boxes and has been clicked.
  $(this).attr('name','Hello world!'); 
  // changes the inner html of this li element which has class boxes and has been clicked.
  $(this).html('Hello world!');

})

それが役に立てば幸い。

于 2013-01-10T00:02:30.927 に答える
1

$(this)要素がクリックされたことに対応するため、クリック イベント コンテキストで使用できます。

var name = $(this).attr('name');  // bears 

var val = $(this).text();       // bees

コード

$('#selectbox li').click(function(){
  var $this = $(this);
  var $btn = $this.addClass('active');
  var name = $this.attr('name');
  var txt = $this.text();
  console.log("Name Attribute - " + name + " :: Text - "+ txt); 
});

働くフィドル

また、ドキュメントが検証され、標準的な慣行に準拠するように、カスタム属性にデータ属性を使用することをお勧めします。

そう

<li class="boxes" name="bears">bees</li>

次のように見えるはずです

<li class="boxes" data-name="bears">bees</li>

.attr()アクセスするには、または.data()メソッドのいずれかを使用できます

var name = $this.attr('data-name');
var name = $this.data('name');
于 2013-01-09T23:56:36.493 に答える
1

これは次のように簡単です。

$('#myOL li').click(function(){
    $(this).addClass('active');
    var name = $(this).attr('name');
    var text = $(this).text(); 
});
于 2013-01-09T23:58:30.580 に答える