英文:
How to add an action listener for a <li> tag using its id?
问题
我正在创建一个li标签,一旦用户点击它,它将使用JavaScript在控制台上发布一些内容。
这是我的index.html:
<!-- 开始片段:不隐藏 js 控制台: true 不使用 Babel: false -->
<!-- 语言: lang-js -->
$('#Title').on('click', function(){
console.log("List was clicked.");
});
<!-- 语言: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="Title"> List 1 </li>
<li id="Title"> List 2 </li>
<li id="Title"> List 3 </li>
<!-- 结束片段 -->
但它没有任何作用,有什么解决方法吗?
英文:
I am creating a li tag that once the user clicks it, it will post something on the console using javascript.
Here is my index.html:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('#Title').on('click', function(){
console.log("List was clicked.");
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="Title"> List 1 </li>
<li id="Title"> List 2 </li>
<li id="Title"> List 3 </li>
<!-- end snippet -->
But it doesn't do anything, are there any approach to this?
答案1
得分: 0
问题出在您在列表中的每个项目上使用相同的 'id' 属性。它必须在文档中是唯一的。如果您想要相同的名称,可以使用类。请参见下面的示例:
HTML:
<li class="Title">List 1</li>
<li class="Title">List 2</li>
<li class="Title">List 3</li>
JS:
$('.Title').on('click', function(){
console.log("List was clicked.");
});
英文:
The issue is because you are using the same id
attribute for each item in the list. It has to be unique in the document. You can use a class if you want to give the same name. See Example below:
HTML:
<li class="Title">List 1</li>
<li class="Title">List 2</li>
<li class="Title">List 3</li>
JS:
$('.Title').on('click', function(){
console.log("List was clicked.");
});
答案2
得分: 0
你不能拥有具有相同ID的多个标签
<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-js -->
$('#Title2').on('click', function(){
console.log("List 2 was clicked.")
});
<!-- 语言: lang-html -->
<li id="Title1"> List 1 </li>
<li id="Title2"> List 2 </li>
<li id="Title3"> List 3 </li>
<!-- 结束代码片段 -->
英文:
You cannot have multiple tags that have a same ID
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('#Title2').on('click', function(){
console.log("List 2 was clicked.") });
<!-- language: lang-html -->
<li id="Title1"> List 1 </li>
<li id="Title2"> List 2 </li>
<li id="Title3"> List 3 </li>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论