将变量从while循环传递到jquery [英] Passing a variable from within a while loop to a jquery
问题描述
我有一个网页,列出了MYSQL数据库中的许多公司,该列表只显示了该公司的名称。当用户点击公司名称时,jquery accordion滑块会显示该公司的其他信息。
I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
当点击公司名称时,它还会向php脚本发送请求记录一个人查看过该公司的详细信息。
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
我的问题
我想将每条记录的ID发送给PHP脚本。
I want to send the ID for each record to the php script.
我通过在while循环中包含手风琴jquery代码来读取mysql查询的输出来实现这一点,但是它生成了许多不必要的源代码(即列出的每家公司)。
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
我需要在while语句之外包含jquery手风琴代码。
I need to include the jquery accordion code outside of the while statement.
如何在jquery代码中将每个数据库记录的ID(即公司名称)传递给$ .post,当它超出时间范围时循环?
手风琴Jquery代码
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
欢迎任何想法。
推荐答案
当您创建HTML时(我假设您也在循环中执行此操作),添加一个数据 - *
属性,其ID为单击元素的值,并在单击元素时使用jQuery读取该值。
When you create the HTML (I assume you do that in the loop as well), add a data-*
attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
例如生成的HTML将如下所示:
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
和你的JavaScript:
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
这篇关于将变量从while循环传递到jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!