getElementById在有序列表中

时间:2012-07-30 16:31:53

标签: jquery getelementbyid

我在html中有这个:

<ul class="ei-slider-arrows">
  <li id="arrowLeft" ><img src='images/close.png'/></li>
  <li id="arrowRight" ><img src='images/close.png'/></li>
</ul>

我正在尝试在我的两个“箭头”上添加一个点击功能,但我无法选择它们。我试过这个:

this.$arrows     = this.$el.find('ul.ei-slider-arrows');
this.$arrowLR    = this.$arrows.children('li');
this.$arrowRight = this.$arrowLR.getElementById("arrowRight");

我可以在this.$arrowLR上添加一项功能,但我无法选择arrowRight。 我尝试使用getElementById,但我也尝试使用get(0)get(1)

任何人都知道它为什么不起作用?

如果我console.log(this.$arrowRight),则只会在控制台中显示[]两种情况(get()getElementById("arrowRight"))。

4 个答案:

答案 0 :(得分:2)

如果您想通过ID获取它们,请使用以下代码段:

var arrowsBoth = $('#arrowLeft, #arrowRight');

或者如果您想单独访问它们:

var arrowLeft = $('#arrowLeft');
var arrowRight = $('#arrowLeft');

你也可以像这样得到它们(同样,这可能会返回比预期更多的元素):

var arrows = $('ul.ei-slider-arrows li');

答案 1 :(得分:2)

只需按ID选择元素并将事件处理程序绑定到它

使用jQuery

$('#arrowLeft').click(function(){

})

$('#arrowRight').click(function(){

})

答案 2 :(得分:0)

我会去:

$("#leftArrow").click(hazaa());
$("#rightArrow").click(hazaa());

function hazaa(){ }

如果您想要执行稍微不同的事情,也可以传递参数,具体取决于点击的箭头。

$("#leftArrow").click(hazaa("left"));
$("#rightArrow").click(hazaa("right"));

function hazaa(direction){ alert(direction); }

答案 3 :(得分:0)

jquery中的

$("#arrowRight")$("#arrowLeft")应该可以获得左右箭头。然后,您可以使用on()delegate()click()来分配处理程序。您也可以document.getElementById("arrowLeft")document.getElementById("arrowRight")进行相同的选择。上面的一个问题是在this.$arrowLR.getElementById("arrowRight");中你试图在包含dom元素列表的jquery对象上使用javascript函数。

相关问题