如何通过单击特定段落来激活事件

时间:2018-03-28 00:19:07

标签: javascript jquery html css

我有这个功能:

$(document).ready(function(){

 $("p").click(function(){
     alert("The paragraph was clicked.");
 });
});

它有效,但我想将其限制为特定段落,例如:

<p class="titleM" id="tituloExist">ENTER WITH A NEW ACCOUNT</p>

2 个答案:

答案 0 :(得分:2)

您可以按ID或班级选择您想要的内容

&#13;
&#13;
// by Class
$("p.titleM").click(function(){
   alert("By Class");
});

// by ID
$("p#tituloExist").click(function(){
   alert("By ID");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="titleM" id="tituloExist">ENTER WITH A NEW ACCOUNT</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在选择器中添加段落的id

&#13;
&#13;
$(document).ready(function(){
 $("p#tituloExist").click(function(){
     alert("The paragraph was clicked.");
 });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="titleM" id="tituloExist">ENTER WITH A NEW ACCOUNT</p>
&#13;
&#13;
&#13;