简体   繁体   English

如何将值传递给javascript onclick到jQuery函数

[英]How to Pass values javascript onclick to jquery function

I have this this image with onclick function on it 我有这张图片,上面有onclick函数

<img id='1213' src='img/heart.png' onclick='heart(this.id)'>

which to call this function : 该调用哪个函数:

function heart(id) {
    $('#heart').dialog('open');
    return false;
}

How can i show the ID inside the div? 如何在div中显示ID?

<div id="heart">
     Name : ABC
     ID : The ID need to be here 
</div>

P/S : i have reason why i want to use the onclick instead directly using the jquery get val from the image id directly. P / S:我有理由为什么我想直接使用onclick而不是直接使用jquery get val从图像id上。

Firstly, you should use JavaScript to attach your events. 首先,您应该使用JavaScript附加事件。 You've already included jQuery, so we may as well use that. 您已经包含了jQuery,因此我们也可以使用它。 Once you attach the event, you can use the text() method to set the innerText property of the span within the target div. 附加事件后,可以使用text()方法在目标div中设置span的innerText属性。 Try this: 尝试这个:

<img id="1213" class="heart" src="img/heart.png" />

<div id="heart">
     Name : ABC
     ID : <span></span>
</div>
$('.heart').click(function() {
    $('#heart span').text(this.id).dialog('open');
});

To show image id, You can use 要显示图片ID,您可以使用

$('#heart').html(id).dialog('open'); 

I would recommend you not to use ugly inline event handler. 我建议您不要使用难看的内联事件处理程序。 You can bind event using jQuery. 您可以使用jQuery绑定事件。 Here I have added a CSS class to img element then we can use Class Selector $(".class") to bind event 在这里,我向img元素添加了一个CSS类,然后我们可以使用Class Selector $(".class")绑定事件

HTML 的HTML

<img class="myImage" id='1213' src='img/heart.png'>

Script 脚本

$(function() {          
    $('.myImage').on('click', function(){
        $('#heart').html(this.id).dialog('open'); 
    });
});

You can do it like this. 您可以这样做。

 function heart(id) { $('#heart').text(id).dialog(); return false; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script> <img id='1213' src='img/heart.png' onclick='heart(this.id);'> <div id="heart"> </div> 

If you are using HTML5, you could make use of data-* attribute. 如果您使用的是HTML5,则可以使用data- *属性。

<img id="someid" src="img/heart.png" data-id="1213"/>

    $('#someid').click(function(e) {
        var id = this.getAttribute("data-id");
        $('#heart').text(id).dialog('open');
    });

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

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