简体   繁体   English

如果我输入的HTML ID是字符串+ php变量,如何在Jquery中进行Onclick事件?

[英]How to make Onclick event in Jquery if my input HTML id is string + php variable?

Hi i've searched alot in Internet about accessing html tag using Jquery if the html tag's id or Class have string and php variable for Example: 嗨,我在Internet上搜索了很多有关使用Jquery访问html标签的信息,例如html标签的id或Class是否具有字符串和php变量,例如:

<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php $value1["ID"] ?>" />

Normally if i havn't a php variable inside the HTML id or class would be in Jquery like that: 通常,如果我在HTML id或class中没有一个php变量,将在Jquery中这样:

$(document).ready(function (e) {
$("#id").on('click', function () {
//some code

});

});

with any help i'll be Thankful. 在任何帮助下,我都会感激不尽。

$(".clicked").click(function() {
    alert("Button #"+$(this).attr("id")+" was pressed!");
});

Try this.. you just need to use this to get to know which button was pressed 试试这个..你只需要使用这个来了解哪个按钮被按下

You can achieve this by not encoding data into the id but instead adding a data- attribute: 您可以通过不将数据编码到id中,而是添加data-属性来实现此目的:

<input type='button' class='idbutton' data-id='<?php $value1["ID"] ?>'>

and then 接着

$(".idbutton").click(function() { 
    var id = $(this).data("id"); 
});

html : html:

<input type='button' value='Save' class='btn btn-warning clicked newClassName' data-id="id_<?php $value1["ID"] ?>" />

Jquery: jQuery的:

$(".newClassName").on("click",function(){
var id = $(this).attr("id");
//Here you get the id also and you can do the processing.

})

Try this: 尝试这个:

your input: 您的输入:

<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php echo $value1 ?>" />

JS code: JS代码:

$(document).ready(function (e) {
    $("#id_<?php echo $value1 ?>").on('click', function () {
    //some code
        console.log('clicked');
    });
});

where $value1 is your php variable 其中$value1是您的php变量

EDITED Example: on php file index.php I've tested below code and it's working 编辑示例:在php文件index.php我已经测试了以下代码,并且可以正常工作

<?php
$value1 = 35;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php echo $value1 ?>" />

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
    $("#id_<?php echo $value1 ?>").on('click', function () {
        //some code
        console.log('clocked');
    });
});
</script>
</body>
</html>

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

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