man*_*che 4 html javascript css jquery
我有一个小的 jquery 问题:
我的代码是这样的:
<div id="select-word-5" class="select-word-link"> - some content - </div>
<div id="select-5" class="select"> - some content - </div>
Run Code Online (Sandbox Code Playgroud)
我在整个文档中有几个 select-word-link 和 select div。
我想向第一个 div 添加一个点击事件,它只对第二个 div 做出反应。
我的想法是遍历所有“select-x”元素,但我认为有更好的方法吗?
$('.select-word-link').each(function()
{
var id = this.id;
var idLink = this.id.replace("-word", "");
$('.select').each(function()
{
if (idLink == this.id)
{
$(id).click(function() {
alert("this does not work");
});
});
});
Run Code Online (Sandbox Code Playgroud)
您可以通过触发对事件的操作来更轻松地完成此操作。
$('#select-5').click(function(){
alert('Does this work?');
});
$('.select-word-link').click(function(){
$('#select-5').trigger('click'); // will behave as if #select-5 is clicked.
});
Run Code Online (Sandbox Code Playgroud)
信息:http : //api.jquery.com/trigger/
更先进:
$('#select-5').click(function(){
alert('Does this work?');
});
$('#select-6').click(function(){
alert('Does this work?');
});
// etc
$('.select-word-link').click(function(){
var selectId = this.id.replace('-word', '');
$('#'+selectId).trigger('click'); // will behave as if #select-5 is clicked.
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38000 次 |
| 最近记录: |