这是我自己的插件的一个例子。
当field1点击时,数据来自表1。
当field2点击时,数据来自表2。
现在当我点击“点击我”按钮点击事件触发多个
次。 请帮助
这是我的html代码文件index.php
<div><a href="#" tableName="table1" id="field1">Field 1</a><br><br></div>
<div><a href="#" tableName="table2" id="field2">Field 2</a><br><br></div>
<!-- feedback of each click event -->
<div id="table">
</div>
<!-- plugin.js file code -->
<script>
(function($){
$.fn.jQtable = function(options){
var self=$(this);
var settings = $.extend({
tableName:'table',
}, options );
self.html('<a href="#" id="secondClick">Click me</a> <br>'+settings.tableName);
$('body').on('click', '#secondClick', function(event) {
event.preventDefault();
alert('works!');
});
};
}(jQuery));
</script>
<!-- main.js file -->
<script type="text/javascript">
$('#field1').on('click', function(event) {
event.preventDefault();
var self=$(this);
var tableName=self.attr('tableName'); // get table name
$('#table').jQtable({
tableName:tableName // send table name
});
});
$('#field2').on('click', function(event) {
event.preventDefault();
var self=$(this);
var tableName=self.attr('tableName');
$('#table').jQtable({
tableName:tableName
});
});
</script>
答案 0 :(得分:2)
您应该将事件与self
对象绑定,而不是body
。
修改后的代码
self.html('<a href="#" class="secondClick">Click me</a> <br>' + settings.tableName);
$('.secondClick', self).on('click', function(event) {
event.preventDefault();
alert('works!');
});
(function($) {
$.fn.jQtable = function(options) {
var self = $(this);
var settings = $.extend({
tableName: 'table',
}, options);
self.html('<a href="#" class="secondClick">Click me</a> <br>' + settings.tableName);
$('.secondClick', self).on('click', function(event) {
event.preventDefault();
alert('works!');
});
};
}(jQuery));
$('#field1').on('click', function(event) {
event.preventDefault();
var self = $(this);
var tableName = self.attr('tableName'); // get table name
$('#table').jQtable({
tableName: tableName // send table name
});
});
$('#field2').on('click', function(event) {
event.preventDefault();
var self = $(this);
var tableName = self.attr('tableName');
$('#table').jQtable({
tableName: tableName
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><a href="#" tableName="table1" id="field1">Field 1</a>
<br>
<br>
</div>
<div><a href="#" tableName="table2" id="field2">Field 2</a>
<br>
<br>
</div>
<!-- feedback of each click event -->
<div id="table">
</div>