5

span同じクラスのタグがいくつかあります。すべてspanに一意のIDがあります。span次に、クリックしたクラスのコンテンツとIDを取得したいと思います。

クラスのIDをどのように処理するかを知りましたが、<span></span>タグ間のコンテンツを取得できないようです。this.html()、、を試しましたがthis.html、テキストを取得できません。this.textthis.tex()

$(".row").click(function() {
    alert(this.id);
    alert(this.html);
}

HTML:

<div>
    <span class="row" id="1">Username of user 1</span>
    <span class="row" id="2">Username of user 2</span>
<div>
4

8 に答える 8

4

あなたidのは無効です(数字で始めることはできません)ので、それらを変更してこれを試してください

<div id="parent">
    <span class="row" id="s1">Username of user 1</span>
    <span class="row" id="s2">Username of user 2</span>
    ...
</div>

jQuery

$("#parent").on('click', '.row', function() {
    alert(this.id);
    alert(this.innerHTML);
});

そうすることで、を使用event delegationして、親のクリックイベントをキャプチャし、ハンドラーを1回だけ定義します(すべての場合、コストがかかるわけではありませんspan) 。

于 2012-05-30T07:57:46.953 に答える
3

.html()要素のコンテンツを取得する機能を利用する

$(".row").click(function() {
    alert(this.id);
    alert($(this).html());
});

作業デモ

于 2012-05-30T07:53:37.117 に答える
2

あなたは使うことができましinnnerHTMLた、そしてあなたはついに逃し);ました。

$(".row").click(function() {
    alert(this.id);
    alert(this.innerHTML);
});
于 2012-05-30T07:56:22.070 に答える
2

こちらをご覧ください。http://jsfiddle.net/2aA92/1/

$(".row").click(function() {
  alert(this.id);
  alert($(this).text());
});​
于 2012-05-30T07:58:05.817 に答える
1
id = $(this).attr('id');
html = $(this).html();
于 2012-05-30T07:53:48.110 に答える
0
$(".row").click(function() {
    alert(this.id);
    alert($(this).text()); // or this.innerHTML
}
于 2012-05-30T07:53:54.100 に答える
0

代わりにこれが必要です:

$(".row").click(function() {
    alert($(this).attr('id'));
    alert($(this).html());
}

<div>
    <span class="row" id="1">Username of user 1</span
    <span class="row" id="2">Username of user 2</span
<div>
于 2012-05-30T07:54:22.750 に答える
0

これを試して:

window.onload = function() {
  $(".row").click(function() {
    alert(this.id);
    alert($(this).html());
  });
}
于 2012-05-30T08:05:30.500 に答える