【问题标题】:easy way to assign function onclick - javascript分配功能 onclick 的简单方法 - javascript
【发布时间】:2013-02-10 15:15:41
【问题描述】:

我现在正在寻找很多时间,寻找一种非常简单有效的方法来通过单击 javascript(不是 jQuery)中的按钮来分配函数。

我遇到的问题是: 1.有时 dom 尚未创建,并且 javascript 函数中有未定义的变量。 2.我不能以正确的方式将属性传递给这个函数。

所以基本上我有这些:

<div class="container">
    <button type=button class="click">Click</button>

    <div class="smallContainer">
        <img src="source.com" class="myimage">
        <div class="data"> some data</div>
    </div>
</div>

<div class="container">
    <button type=button class="click">Click</button>

    <div class="smallContainer">
        <img src="source.com" class="myimage">
        <div class="data"> other data</div>
    </div>
</div>


<div class="container">
    <button type=button class="click">Click</button>

    <div class="smallContainer">
        <img src="source.com" class="myimage">
        <div class="data"> usefull data</div>
    </div>
</div>


for (){ assign in each button the onclick function}

function onclick(){
        here i want to change the opacity of the image by the class "myimage",
        take the innerHTML of the div by the class "data" and do something to it(maybe i ll send an ajax request in this function also)
    }

所以我需要一个 for 循环或其他东西(可能在 javascript 文件中),它将分配给所有按钮这个函数。每次单击按钮时,我都需要知道哪个按钮是什么以及“数据”类的 div 里面有什么功能。

我尝试了很多方法,每一种都有问题。任何人都可以提供一个简单的工作解决方案吗?

谢谢

【问题讨论】:

  • 如果您使用 jQuery 或其他库,您的工作会更轻松。有什么东西会阻止你使用 js 库吗?
  • 为此,jQuery 是显而易见的选择。 $function() { $(".click").on("click", function() { $(this).whateveryouwant... }); });如果您将 Ajax 添加到混合中,那么几乎没有讨论
  • 唯一阻止我的是,我很快就有了最后期限,而且我知道 javascript 基础知识,但根本没有 jQuery 或其他库。而且我必须在函数内部做很多事情。
  • @Vlenorroia,如果您有更多与 DOM 操作相关的任务,学习 jQuery 或其他库将为您节省大量时间。学习它们很容易。只需按照示例进行操作。另一种选择是为自己编写一些简单的库,但这需要一些时间和精力。如果你选择后者,那么这个网站将是你最好的朋友quirksmode.org。检查兼容性表以了解浏览器支持和不支持的内容。

标签: javascript function button onclick assign


【解决方案1】:

既然您提到您不具备使用纯 JavaScript 完成此简单操作的技能,那么是时候将 jQuery 添加到您的工具箱中了。

这里是你需要的所有代码

 $function() { // when the page is ready
   $(".click").on("click", function(e) { // assign a function to ALL class="click" 
     var id = this.id; // or $(this).attr("id"); - if you need the button's ID
     var divContent = $(this).parents().find(".data").html()
     $.get("someserver.php",{"id":id,"parm":divContent},function(data) {
       alert(data);//  from server
     });
   });
 });

【讨论】:

  • 好的,我想我明白这一点,但最后一个函数(数据)是什么?它有什么作用,什么是数据属性?
  • 数据从服务器调用传递给函数(数据)。它是您的服务器在使用参数调用时发送的任何内容
【解决方案2】:

尝试使用 jquery 库 :) 那样你可以做类似的代码

<script>
$(".data").click(function(){
  var class_value = $(this).html();
})
</script>

如您所见,该函数将应用于所有具有“数据”类的元素

【讨论】:

  • 因为我想在被调用的函数内部,对有按钮的 div 做很多事情,我更喜欢 javascript,因为我知道一些基础知识,而 jQuery 我不知道 tall :)
  • 糟糕的例子,因为 .val() 用于输入,而 click 是他的类的名称
猜你喜欢
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多