简体   繁体   English

JavaScript中的php vars

[英]Php vars within javascript

I have a bit of code to record a certain action 我有一些代码来记录特定的动作

$('#record').click(function(){
$.get("../confirm.php", { "id": '<?php echo $record; ?>' }, function(data){});
});

Which works fine, but i don't want the page to be full of javascript and such as i have other things like this on it too, so i am trying to move it to a js file. 哪个工作正常,但我不希望页面充满JavaScript,例如我也有其他类似的东西,所以我试图将其移至js文件。

In the php file 在php文件中

<script type="text/javascript">var record = "<?= $record ?>";</script>
<script type="text/javascript" src="jsfile.js"></script>

In the js file 在js文件中

$('#record').click(function(){
$.get("../confirm.php", { id: record}, function(data){});
});

But it doesnt want to play ball, any ideas how to do this? 但是它不想打球,有什么想法怎么做?

Make 'record' as class of div and assign php variable $record as its id.Use event.target.id to get variable $record from div. 将'record'作为div的类,并将php变量$ record分配为其id。使用event.target.id从div获取$ record。

<div class="record" id="<?php echo $record;?>">
 Your code here
</div>

And Use this $('.record').click(function(event){ var record=event.target.id; //your code here }); 并使用此$('。record')。click(function(event){var record = event.target.id; //此处是您的代码});

If I may a suggestion to you. 如果我有建议的话。 Set in the view on the element the ID. 在元素的视图中设置ID。 Then when the action is clicked, get the id for the data. 然后,当单击操作时,获取数据的ID。

Example: 例:

<input type="text" name="inputName" id="<?php echo $record; ?>" class="btnToRecord" />

$('.btnToRecord').click(function(){
    var clickedElement = $(this);
    $.get("../confirm.php", { id: clickedElement.attr("id") }, function(data){});
});

Edit: Correction for $(this) was pointing to the get instead to the element, putting in a var will fix the problem 编辑:$(this)的更正指向get而不是元素,放入var将解决问题

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

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