使用 on() 或 bind() 时如何获取选择器的属性?
How to get attributes of a selector when using on() or bind()?
我有一个网页,其中列出了数据库中的一些文章。内容通过 ajax.
动态加载
每篇文章都有一个编辑按钮,它会动态弹出一个编辑器(第二次 ajax 调用),用户可以在其中对文章进行更正。
我的问题是我需要在按下编辑按钮时传递文章的'id'(以便将其加载到编辑器window),但是因为我需要使用bind() 使按钮工作没有办法获得按钮(选择器)的任何属性,如 'href':
$('body').on ('click', '.button', function (){
//load editor window
});
那么我怎么能在这里引用“.button”来使用 .attr () 获取它的属性呢。
谢谢!
我假设您的 HTML 以这种方式呈现:
<div id="article_1">
<button class="button">Edit</button>
</div>
<div id="article_2">
<button class="button">Edit</button>
</div>
<div id="article_3">
<button class="button">Edit</button>
</div>
如果是这样,那么你的JS应该是这样的:
$('body').on('click', '.button', function () {
var id = $(this).parent().attr("id");
alert(id);
});
您需要使用 e.preventDefault();
来确保您没有触发默认事件,即 href
标签中的 URL。
$('body').on ('click', '.button', function (e){
e.preventDefault();
console.log($(this).attr('href'));
});
我有一个网页,其中列出了数据库中的一些文章。内容通过 ajax.
动态加载每篇文章都有一个编辑按钮,它会动态弹出一个编辑器(第二次 ajax 调用),用户可以在其中对文章进行更正。
我的问题是我需要在按下编辑按钮时传递文章的'id'(以便将其加载到编辑器window),但是因为我需要使用bind() 使按钮工作没有办法获得按钮(选择器)的任何属性,如 'href':
$('body').on ('click', '.button', function (){
//load editor window
});
那么我怎么能在这里引用“.button”来使用 .attr () 获取它的属性呢。
谢谢!
我假设您的 HTML 以这种方式呈现:
<div id="article_1">
<button class="button">Edit</button>
</div>
<div id="article_2">
<button class="button">Edit</button>
</div>
<div id="article_3">
<button class="button">Edit</button>
</div>
如果是这样,那么你的JS应该是这样的:
$('body').on('click', '.button', function () {
var id = $(this).parent().attr("id");
alert(id);
});
您需要使用 e.preventDefault();
来确保您没有触发默认事件,即 href
标签中的 URL。
$('body').on ('click', '.button', function (e){
e.preventDefault();
console.log($(this).attr('href'));
});