获取点击的

时间:2015-07-18 06:06:34

标签: javascript php jquery html

这是来自php数据库的数据的列表表示。使用foreach php循环获取列表,并相应地填充achor标记内的数据。

<?php foreach($array as $iterate):?>
 <div class="col-sm-3">
  <div class="panel panel-default">
   **<a onClick='theFunction();' id="hello" href="#myModal" style="text-decoration:none;">**
    <div class="panel-heading">
     <img src ="audi_sillhouete.jpg" style="height:100%; width:100%;">
       <p id="10" style="position:absolute; top:10%; padding-left:5%; padding-right:15%;"><?php echo $iterate->test_name ?></p>
    </div>
   </a>                    
  </div>
</div>
<?php endforeach;?>

正如您在此处所看到的,在锚标记内部,我已将其隐藏到模式框中,只要用户点击任何链接,该框就会显示一条消息。模态窗口中有一个按钮,可以将用户带到另一个页面。 问题是我想传递某个值和url,但是不能这样做,因为在模态窗口规范部分中定义了到下一页的链接。 所以我提出了这个解决方案。我想到使用锚标记的id属性,我试图获取使用javascript点击的锚点的id属性。

<script type="text/javascript">
 function theFunction()
 {
    var id = $('a', this).attr('id');
    alert(id);
 }</script>

从此我想初始化一个php变量,然后使用该php变量作为模式窗口按钮的href中的值传递。但由于某种原因,我在警报框中获得的值是“未定义的”。我已经尝试了所有可能的组合。

$('a',this).attr('id');
$this.id;

一切都回归'未定义'。

参考 - 这是模态窗口部分的代码。

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Instructions</h4>
      </div>
      <div class="modal-body">
       Your test is about to commence. A timer will be initiated after the moment you start the test. You may choose to answer a question, or leave it empty. You can also attempt the questions in any order that you find suitable.<br><br>Upon completion of the test, click on "Submit" to see your performance statistics.<br><br><br>Good luck!
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <a href="../test/pretest.php?test=<?php echo $testname?>" style="text-decoration:none;color:white;"><button type="button" class="btn btn-primary">Continue</button></a>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

3 个答案:

答案 0 :(得分:3)

请尝试此

$(document).on('click', 'a', function () {
    alert(this.id);
});

DEMO

答案 1 :(得分:1)

你可以在锚中使用其他属性,如:

<a href='' id='hello' para-id='somevalue'></a>

alert($("#hello").attr("para-id"));

答案 2 :(得分:1)

以下jQuery函数在页面加载时运行所有a标记,并将id添加到链接的末尾。

$(function(){
    $('a').each(function(){
        var id = $(this).attr('id');
        var url = $(this).attr('href') + '?id=' + id;
        $(this).attr('href',url);
        });
});

https://jsfiddle.net/yc1hswet/