我有一个小的 jquery 问题:
我的代码是这样的:
<div id="select-word-5" class="select-word-link"> - some content - </div>
<div id="select-5" class="select"> - some content - </div>
我的文档中有几个 select-word-link 和 select div。
我想向第一个 div 添加一个点击事件,它只对第二个 div 使用react。
我的想法是遍历所有“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");
});
});
});
最佳答案
您可以通过对事件触发操作来更轻松地做到这一点。
$('#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.
});
信息: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.
});
关于javascript - jQuery:将点击事件添加到特定的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252332/