简体   繁体   English

如何在jquery中使用JavaScript实例/通过jquery选择JavaScript句柄?

[英]How to use a javascript instance in jquery/Select a javascript handle via jquery?

As a jquery-beginner, i should bind a javascript object into my jquery functions, like: 作为一个jquery初学者,我应该将一个javascript对象绑定到我的jquery函数中,例如:

<div title="StackOverflow" onclick="javascript:action(this)">Content</div>

and in action i will handle the "this" : 在行动中,我将处理“ this”:

function action(instance){
example=instance.attr("title");
}

but the "instance" is not a jquery object so i can't work with it. 但“实例”不是jquery对象,因此我无法使用它。 The syntax 语法

example=$(instance).attr("title");

doesn't help me either. 也不帮我

I'd be glad of any suggestions 我很高兴有任何建议

If you're using jQuery then you should completely separate the definition of your HTML and associated JavaScript. 如果您使用的是jQuery,则应将HTML和相关JavaScript的定义完全分开。 For example 例如

HTML: HTML:

<div id="soDiv" title="StackOverflow">Content</div>

JavaScript: JavaScript的:

$(document).ready(function() {
  $('#soDiv').click(function() {
    var example = $(this).attr('title');
    ...
  });
});
// HTML file
<div title="StackOverflow" id="stackoverflow">Content</div>
// JS File
document.getElementById("stackoverflow").addEventListener("click", function () {
  var example = this.getAttribute("title");
});

Seperations of concerns 关注点分离

this should work... 这应该工作...

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
        <script>
            function action(instance){
                example=$(instance).attr("title");
                alert(example);
            }
        </script>
    </head>

    <body>
        <a id="test" title="StackOverflow" onclick="javascript:action(this)" href="#">Content</a>
    </body>
</html>

HTML: HTML:

<div title="StackOverflow" id="stack">Content</div>

Javascript (with jQuery): Javascript(使用jQuery):

$('#stack').click(function(){
    alert(this.title);
});

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

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