如何选择使用Jquery作为参数传入的DOM元素

时间:2012-07-13 20:20:54

标签: javascript jquery

所以我有

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

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

我如何使用Jquery选择器来选择范围?我尝试了$(theSpan),但它不起作用。我想选择它作为Jquery对象,以便我可以将attr()应用于它。

谢谢!

2 个答案:

答案 0 :(得分:1)

$(theSpan).attr('test, '123');效果很好。

你的问题出在其他地方。

答案 1 :(得分: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