为什么我的可点击的div工作作为此代码的链接

时间:2015-07-14 09:28:28

标签: jquery html

这是我的jQuery代码:

$('.projektet').click(function(){
    var url = $(this).find("a").attr("href");
    window.location = url;
});
<div class='projektet'>
    <h3>".$alias." ".$expertis." ".$other."</h3>
    <h3>".$headline."</h3>
    <p>".$desc."</p>
    <a href='posts.php?id=".$id."'></a>
</div>

CSS:

.projektet{
    min-height: 200px;
    width: 90%;
    margin: 0px auto;
    cursor: pointer;
}

整个php文件

<?php
     include("./inc/connect.inc.php");
     $sql = $mysqli->query("SELECT * FROM projekt WHERE sort='startup' ORDER BY id DESC");
    while($row = $sql->fetch_array(MYSQLI_BOTH)){
    $alias  = $row['användare'];     $id = $row['id'];
    $headline = $row['headline'];
    $desc = $row['beskrivning'];
    $expertis = $row['expertis'];
    $other = $row['annat'];


    echo "<div class='projektet'><h3>".$alias." ".$expertis."".$other."</h3><h3>".$headline."</h3><p>".$desc."</p><a href='posts.php?id=".$id."'></a></div>";
}

?>

我在点击后直接尝试的提示没有发出警告,所以问题必须在于找到div,我觉得应该没问题。

2 个答案:

答案 0 :(得分:1)

jquery:

var p1=$(".widgetInfobox[possition='1']").html();
alert(p1); 

HTML / PHP:

$('.projektet').click(function(){
    var url = $(this).find("a").attr("href");
    window.location.href = url;
});

这些工作正常,请确保:

  1. 验证您的代码:validator.w3.org
  2. 将您的jQuery放在<div class='projektet'> <h3>".$alias." ".$expertis." ".$other."</h3> <h3>".$headline."</h3> <p>".$desc."</p> <a href='posts.php?id=".$id."'></a> </div> 函数中:ready
  3. 如果您想调试以确保href实际上是您想要使用的:$(document).ready(function(){});

    编辑:以下是此代码正常工作的证据:

    &#13;
    &#13;
    console.log($(this).find("a").attr("href"));
    &#13;
    $(document).ready(function() {
      $('.projektet').click(function(){
           var url = $(this).find("a").attr("href");
           alert(url);
          //window.location.href = url;
        });  
    });
    &#13;
    &#13;
    &#13;

答案 1 :(得分:-2)

&#13;
&#13;
$('.projektet').click(function(){
    var url = $(this).find("a").attr("href");
    window.location.href = 'https://codeclimate.com/';
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='projektet'>
  <h3>some text here</h3>
  <h3>Some Text</h3>
  <p> some text</p><a href='https://google.com'></a></div>
&#13;
&#13;
&#13;