简体   繁体   English

如何使用jQuery在div onclick属性中获取字符串?

[英]How to get the string in div onclick attribute with jQuery?

I have a banner which is something like this: 我有一面这样的横幅:

<ul id="carousel">
   <li id="item1">
      <div onclick="window.open('mylinkhere.com,'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
      </div>
   </li> 
   <li id="item2">
      <div onclick="window.open('myotherlinkhere.com,'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
      </div>
   </li> 
</ul>

I need to access the links written in onclick attribute ie mylinkhere.com 我需要访问用onclick属性编写的链接,即mylinkhere.com

I tried 我试过了

var banners = $($("#carousel")[0]).children().filter("li");
var b_items = $(banners[0]).children().filter("div");
attr_val = $(".b_items")[0].attr("onclick");

But i couldn't. 但是我不能。 By the way i don't know from the start that which item will be in the carousel because it's randomized by another function. 顺便说一句,我从一开始就不知道哪个项目会在轮播中,因为它是由另一个函数随机分配的。 So i cannot access them with item1 item2 ect. 所以我无法使用item1 item2 ect访问它们。

Thanks. 谢谢。

You can set the url in a data attribute and read easily like this: 您可以在data属性中设置url并像这样轻松阅读:

<ul id="carousel">
   <li id="item1">
      <div data-url="mylinkhere.com" onclick="window.open($(this).data('url'),'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
      </div>
   </li> 
   <li id="item2">
      <div data-url="myotherlinkhere.com" onclick="window.open($(this).data('url'),'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
      </div>
   </li> 
</ul>

To read: 读书:

var b_items = $(banners[0]).children().filter("div");
var link = $(b_items).data('url');

See this fiddle: http://jsfiddle.net/Pontual/pugytfwu/ 看到这个小提琴: http : //jsfiddle.net/Pontual/pugytfwu/

For me, the following code works as expected (Chrome 44, jQuery 2.1.3): 对我来说,以下代码可以正常工作(Chrome 44,jQuery 2.1.3):

var s = jQuery('#carousel li div');
s.each(function(i,node) {
    alert(jQuery(node).attr('onclick'));
});

http://jsfiddle.net/aavf1450/ http://jsfiddle.net/aavf1450/

Possible problem is that in your code, you do not wrap the element into $(...), so .attr() is not a valid function, as using indexers on a jQuery object returns raw HTML elements. 可能的问题是,在您的代码中,您没有将元素包装到$(...)中,因此.attr()无效,因为在jQuery对象上使用索引器会返回原始HTML元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM