简体   繁体   English

可以使此javascript不引人注目吗?

[英]Can this javascript be made unobtrusive?

I have this inline javascript, is there any way it could be made unobtrusive? 我有这个内联javascript,有什么办法可以使它不引人注意? thanks. 谢谢。

<a href="/uploads/status/image/52/Zombatar_1.jpg" onclick="displayLightBox(this); return false;">
    <img alt="Thumb_zombatar_1" src="/uploads/status/image/52/thumb_Zombatar_1.jpg">
</a>

Definitely a good idea to keep your HTML markup and JavaScript code separate. 绝对不要将HTML标记和JavaScript代码分开。 I would recommend applying the onClick behavior to the link after it has been rendered. 我建议在呈现链接后将onClick行为应用于链接。 In my example, I use jQuery to bind the event handler function to the link: 在我的示例中,我使用jQuery将事件处理函数绑定到链接:

$('#element_id').click(function() {
    displayLightBox(this);
    return false;
});

If you're writing large web applications, separating your business logic and presentation is essential for writing maintainable and supportable code. 如果要编写大型Web应用程序,则将业务逻辑和表示形式分离对于编写可维护和可支持的代码至关重要。

Your jQuery selector will vary depending on how it's placed on the page. jQuery选择器将根据其在页面上的放置方式而有所不同。 If you could provide the HTML context in which that link is created, I can provide a better suited jQuery selector. 如果您可以提供在其中创建该链接的HTML上下文,那么我可以提供一个更合适的jQuery选择器。

As you've tagged the question with jQuery, I'll give you a jQuery answer. 当您使用jQuery标记问题后,我将为您提供jQuery答案。 Your a element currently has no identifying characteristic other than its href attribute. a元素目前除其href属性外没有其他识别特征。 It would be easiest to give it an id and then use an id selector. 给它一个id然后使用一个id选择器将是最简单的。 The key is simply find some characteristic by which you can identify the element you want to target. 关键只是找到一些特征,通过这些特征您可以识别要定位的元素。

If an id or a class is not an option, use an attribute selector: 如果不是idclass ,请使用属性选择器:

$("a[href='/uploads/status/image/52/Zombatar_1.jpg']").click(function() {
    displayLightBox(this);
    return false;
});

Notice that I've removed the random false;; 注意,我删除了随机的false;; from your inline event handler as as far as I can tell it serves no purpose whatsoever. 据我所知,从您的内联事件处理程序中获取的信息毫无意义。

Update (see comments) 更新 (请参阅评论)

As you have multiple elements to bind the event handler to, your best bet will probably be a common class. 由于您有多个要绑定事件处理程序的元素,因此最好的选择可能是普通的类。 You can then use a class selector: 然后,您可以使用类选择器:

$(".myLink").click(function() {
    displayLightBox(this);
    return false;
});

The click event handler is bound to all elements in the matched set. click事件处理程序绑定到匹配集中的所有元素。 When it executes, this refers to the clicked element. 在执行时, this指的是clicked元素。

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

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