Php 根据元素更改HREF链接;“价值”;在jquery中
我有以下PHP从my MYSQL表返回记录。这些记录显示为链接。请参阅下面的代码Php 根据元素更改HREF链接;“价值”;在jquery中,php,jquery,mysql,Php,Jquery,Mysql,我有以下PHP从my MYSQL表返回记录。这些记录显示为链接。请参阅下面的代码 <div class="slide1" id="u1026"> <?php while ($row = mysql_fetch_array($query_rental)) { echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"
<div class="slide1" id="u1026">
<?php while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental.php?id={$row['client_name']}\"></a>";
}?>
</div>
我只是不知道该怎么做,这取决于该值是否包含文本“layout2”。非常感谢您的帮助。谢谢您只需在PHP代码中直接完成即可:
while ($row = mysql_fetch_array($query_rental)) {
$layoutFlag = $row['layout'] == 'layout2' ? '-layout2' : '';
echo "<a class='fancybox fancybox.iframe' id='rental' value=\"{$row['layout']}\" href=\"brochures\items-rental{$layoutFlag}.php?id={$row['client_name']}\"></a>";
}
正如您所看到的,只需在PHP中执行它就容易多了
另请注意,您正在使用相同的id
创建多个元素。也许你的意思是class='fancybox fancybox.iframe rental'
另外,我建议使用
data-
前缀保存自定义数据。对于布局,请使用数据布局='layout-which'
。然后,您可以使用.attr('data-layout')
获取布局属性(更容易理解该代码正在做什么!)。您可以在PHP
循环上运行IF
语句
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
- 您所有的链接都具有相同的ID,当您想要使用jQuery时,这可能会导致一些问题
- 如果fancybox类中有更多的a标记,请尝试向这些标记添加唯一的类并更新每个循环
$(function () {
// I'm assuming you are going to turn it into a rental class, otherwise change the selector to whatever.
$("a.rental").each(function() {
var rentalItem = $(this);
if (rentalItem.attr('value') === 'layout2') {
// You can choose what to replace, as long as you know it will replace EXACTLY what you want it to. I'm just going with Regex's ^ (start-of-line) operator to make sure that what we are replacing is at the start of the line...
rentalItem.attr('href', rentalItem.attr('href').replace(/^brochures\\items\-rental/, 'brochures\\items-rental-layout2'));
});
});
while ($row = mysql_fetch_array($query_rental)) {
echo "<a class='fancybox fancybox.iframe' id='rental' value={$row['layout']} href=\"brochures\items-rental".($row['layout'] == 'layout2' ? '-layout2' : '').".php?id={$row['client_name']}\"></a>";
}
$( "a.fancybox" ).each(function( index ) {
if($(this).val() == "layout2") {
oldHref = $(this).attr('href');
newHref = oldHref.replace('items-rental.php', 'items-rental-layout2.php')
$(this).attr('href', newHref);
}
});