我通过onclick属性在元素本身中调用一个函数,因为我需要php在其中一个函数参数中动态给出一个值.当我尝试通过"$(this)"引用函数中的调用元素时,它最终引用整个窗口而不是元素.我该如何解决?
Can*_*var 21
尝试将元素作为参数发送到您的函数,如下所示:
<input type="text" onclick="myfunction(this);"></input>
Run Code Online (Sandbox Code Playgroud)
你的功能应该是:
<script>
function myfunction(currentElement){
// ...
}
</script>
Run Code Online (Sandbox Code Playgroud)
我怀疑你真的需要使用内联onclick属性.您可以通过各种不同的方式将数据存储在元素中.如果不知道你需要传递的参数是什么,很难确切地说你会怎么做,但我会给出一些例子.
最灵活的可能是data-属性:
<a href="#" id="subject" data-type="fiction">Text</a>
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过以下方式访问信息:
$(document).ready(function(){
$('#subject').click(function(){
$type = $(this).data('type'); // this works as of jQuery 1.4.3, otherwise $(this).attr('data-type');
// do your handling here, using $type
});
});
Run Code Online (Sandbox Code Playgroud)
您也可以使用类,创建全局变量的脚本标记,各种方法来完成此操作.这几乎肯定比将jQuery处理程序放在onclick属性中更好.
| 归档时间: |
|
| 查看次数: |
22249 次 |
| 最近记录: |