doumianfeng5065 2015-05-31 18:55 采纳率: 0%
浏览 34
已采纳

根据jquery中的元素“value”更改HREF链接

I have the following PHP that returns records from a my MYSQL table. These records are displayed as LINKS. See code below...

        <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>

What I would like, is for the HREF link to change to

\"brochures\items-rental-layout2.php?id={$row['client_name']}\

If VALUE contains the text "layout2". I know that I can change HREF using jquery code

$(document).ready(function () {  
  $("#event").attr("href", "http://the.new.url")
});

I'm just not sure how to do that depending if the VALUE contains text "layout2". Any help is much appreciated. Thanks

  • 写回答

2条回答 默认 最新

  • dongqiabei7682 2015-05-31 19:02
    关注

    You can just do it straight in the PHP code:

    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>"; 
    }
    

    You could also do it with Javascript:

    $(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'));
      });
    });
    

    As you can see, just doing it in PHP is so much easier.

    Also as a side note, you are creating multiple elements with the same id. Maybe you meant class='fancybox fancybox.iframe rental'?

    And as a second side note, I suggest using the data- prefix for holding custom data. In layout's case, use data-layout='layout-whatever'. You can then use .attr('data-layout') to get the layout attribute (it's easier to understand what that code is doing too!).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值