0

コンテナー内に多数の div があります。divの1つがクリックされると、そのdivのIDとクラス「CURRENT」を持つものを比較し、それらが同じでない場合は何かをします。

「緑」ではなく「赤」クラスが存在するかどうかを確認し、存在する場合はアラートを表示する別の条件を追加したいと思います。以下のコードを試してみましたが、「メイン」の div をクリックするとアラートが表示されるため、チェックが間違っている可能性があると思います...

<div id="main">
   <div id="1"><span class="red"></span>Label 1</div>
   <div id="2"><span class="red"></span>Label 2</div>
   <div id="3"><span class="green current"></span>Label 3</div>
   <div id="4"><span class="green"></span>Label 4</div>
</div>

$('#main div').live('click', function() {

   var ct = $('.current').attr('id');
   var cc = $(this).attr('id');

   // need to add conditional statement
   // if ($(this).find('.red')) {
   //    alert("Has red class");

   if (ct != cc) {
      // do something
   }

});
4

3 に答える 3

3

試す

if ($(this).hasClass('red')) {
   // do something
}

編集: 申し訳ありませんが、これは、クリック イベントがスパン自体から発生することを前提としています。

if ($('span', this).hasClass('red')) {
   // do something
}

動作するはずです...

2番目の編集: divを閉じる必要があります...次に: http://jsfiddle.net/E9948/

于 2012-11-20T13:25:39.600 に答える
1

要素にクラスがあるかどうかを確認する方法は、.hasClass()

if ($('span', this).hasClass('red')){
    alert('has red class');
}

持っていたときに行っていたのは、 class を持つ.find('.red')子孫を取得することです。.hasClass() のようにブール値を返しません。$(this)red

また、あなたdiv idの は数字で始まります。それは正しい方法ではありません。彼らは手紙で始める必要があります。そして、divタグを閉じることをお勧めします。:-)

ここにjsbinがあります

于 2012-11-20T13:27:28.293 に答える
0

代替(作業サンプルhttp://jsbin.com/oqopaw/1/edit):

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
  <style>
    #main span{
      cursor:pointer;
    }
    .red{
      background-color:red;
    }
    .green{
      background-color:green;
    }
  </style>
</head>
<body>
<div id="main">
   <div id="1"><span class="red">Label 1</span></div>
   <div id="2"><span class="red">Label 2</span></div>
   <div id="3"><span class="green current">Label 3</span></div>
   <div id="4"><span class="green">Label 4</span></div>
</div>
<script>
$('#main span').click(function() {
  if($(this).attr('class').indexOf('current') >= 0) 
  {
    if($(this).attr('class').indexOf('green') >= 0) alert('current green!');
  }
});  
</script>
</body>
</html>
于 2012-11-20T13:41:21.777 に答える