将div转换为与JavaScript限制的链接。类和没有id

时间:2015-02-10 06:43:46

标签: javascript jquery html css

我在WordPress父主题中由functions.php生成的短代码生成以下html:

<div class="pricing-table-one left full-width ">
    <div class="pricing-table-one-border left">
        <div class="pricing-table-one-top pricing-table-green left" style="background:#95705b">
            <span style="color:">Restaurant / Café</span>
            <p style="color:"></p>
        </div>
        <div class="pricing-table-one-center pricing-table-white left"> 
            <h5>ONTBIJT</h5>
        </div> 
        <div class="pricing-table-one-center pricing-table-white left">
             <h5>LUNCH</h5>
        </div> 
        <div class="pricing-table-one-center pricing-table-white left">          
            <h5>BRUNCH</h5>
        </div>
        <div class="pricing-table-one-center pricing-table-white left">
            <h5>DINER</h5>
        </div> 
        <div class="pricing-table-one-center pricing-table-white left">  
            <h5>WEST-FRIESE KOFFIETAFEL</h5>
        </div> 
        <div class="pricing-table-one-center pricing-table-white left">
            <h5>SALADESCHOTELS</h5>
        </div>
        <div class="pricing-table-one-center pricing-table-white left">
            <h5>EN NOG VEEL MEER</h5>
        </div>
        <div class="color-buttons color-button-blue pricing-button">
            <a href="mailto:info@domain.nl?subject=Informatie Restaurant">Voor meer informatie – Email ons</a>
        </div>
    </div>
</div>

我需要在单元格中创建一个标题,或者在包含它的div中创建一个pdf链接。我读了here我可以在jQuery的id上这样做:

$("div").click(function(){
   window.location=$(this).find("a").attr("href"); return false;
});

但是只有当你改变html时他才会工作。我更喜欢Jquery或JavaScript解决方案。在CSS技巧上,我找到了另一个可能有帮助的snippet

$(".myBox").click(function() {
  window.location = $(this).find("a").attr("href"); 
  return false;
});

我只需要将a元素更改为div,将类更改为div的类。但是,我需要使用一些特定的div(表中的一些项目,但不是全部)完成它,并且它只有一种有用的类:

<div class="pricing-table-one-center pricing-table-white left"><h5>BRUNCH</h5></div>

也许通过专注于父级div和#34; pricing-table-one&#34;然后是里面的div。但是我仍然需要第n个div或h5标签..

是否可以使用JavaScript或jQuery创建 BRUNCH 或其他h5标签的链接,或者我必须更改为PHP代码服务器端?

2 个答案:

答案 0 :(得分:2)

我没有准确地回答你的问题。

但是,我认为您希望wrap div<a> - 它会使div成为link -

  • 您可以执行类似以下代码的操作。

$(function(){ $( ".pricing-table-one-center" ).wrap( "<a href='#'></a>" ); });

  • .wrap() - wrap()方法在每个选定元素周围包装指定的HTML元素。

答案 1 :(得分:2)

我赞成他的答案,但是,这是我的意思的快速片段。这假设您无法控制html。

$(function () {
  // pdf urls and header names
  var pdfUrls = {
    'BRUNCH': 'http://domain.nl/wp-content/uploads/2015/02/09/x.pdf',
    'DINER': 'http://domain.nl/wp-content/uploads/2015/02/09/y.pdf'
  };

  // loop through each h5 tag within pricing-table-one
  $('.pricing-table-one h5').each(function (i, el) {
    var header = $(el).text();

    // if a header url is found
    if (pdfUrls[header]) {
        $(el).wrap('<a href="' + pdfUrls[header] + '"></a>');
    }
  });
});

这是一个小提琴:http://jsfiddle.net/pbzvszxo/