13

我有一个跨度的 div

<div id="div1">
    <span class="">hello</span>
</div>

当我单击 div 时,我想更改 div 的唯一第一个 span 元素的类

$('#div1').click(function() {
    // ... check if first span element inside the div .. if there and change the class..    
});  
4

5 回答 5

20
$('#div1').click(function() {    
   $('span:first', this).prop('class', 'newClassName');
})

http://api.jquery.com/first-selector/

http://jsfiddle.net/BUBb9/1/

于 2012-04-04T09:30:17.517 回答
7

利用

 $("div span:first-child")

如下:

$('#div1').click(function() {    
   $('span:first', this).prop('class', 'ClassName');
})

参考http://api.jquery.com/first-child-selector/

于 2012-04-04T09:31:49.090 回答
3
$('#div1').click(function(){
    var v = $(this).find('span').text();
});

这样就可以得到 span 的值。

您也可以使用 .html() 代替 .text() 方法。

于 2012-04-04T09:32:09.350 回答
3

多个答案有效。我的做法:

$('#div1').click(function() {    
     $(this).find('span').first().attr('class','newClassName');
});
于 2012-04-04T09:33:37.180 回答
2
$('#div1').click(function() {    
   $('#div1 span:first').attr('class', 'newClassName');
});
于 2012-04-04T09:35:24.680 回答