2012-07-13 71 views
0
DOM元素

所以我如何选择传递作为一个参数使用jQuery

<span onclick="show(this)">foobar</span> 

function show(theSpan) { 
    ....... //select the span here 
} 

我怎么能使用jQuery选择器选择的跨度?我尝试了$(theSpan),但它不起作用。我想选择它作为一个Jquery对象,以便我可以将attr()应用于它。

谢谢!

+0

你说“不工作”的意思。它会抛出任何错误? – Asdfg 2012-07-13 20:25:06

+1

什么是你想要的跨度? – 2012-07-13 20:26:36

+1

yes $(theSpan).attr('test,'123');工作正常。 – eastboundr 2012-07-13 20:28:59

回答

1

$(theSpan).attr('test, '123');工作正常。

你的问题在别的地方。

0

那么,有在你的元素没有属性附加伤害,但只是把你举个例子,假设你有这样的:

<span id="spTest" onclick="show(this);">foobar</span>​ 

这是你能得到像ID的属性附加伤害的方式:

var id = $(theSpan).attr('id'); //outputs: spTest 

但我不知道你在你的问题是什么意思,也许你需要的价值,所以这是得到它的方式:

var spanValue = $(theSpan).html(); //outputs: foobar 

另外,如果你想设置一个id该元素,你可以做到以下几点:

//Set the id 
$(theSpan).attr('id', 'theSpan'); 
//Store the value from your element by the new id 
var spanValue = $('#theSpan').html(); 
//Do what you want at this point 
alert(spanValue); //outputs: foobar