阅读最新jQuery 1.x库的新规范,它说使用.on
来附加动态创建的jQuery元素的事件,但是,我似乎无法完成这项工作。在我$(document).ready
功能我有以下几点:jQuery - 如何让.on事件为动态创建的HTML工作?
的jQuery:
$(".dropdown").on("click", function(event) {
event.preventDefault();
var type = $(this).text() == '[ Read more... ]' ? 'expand' : 'collapse';
var theDiv = type == 'expand' ? $(this).parent().next("div") : $(this).parent().prev("div");
var theId = $(this).attr("id");
$(this).parent().remove();
var vText = theId == 'reqMat' ? 'Every candidate is required to submit a headshot and candidate statement.' : 'To strengthen your candidacy and let people know what you\'re all about, we invite you to create a campaign video.';
theDiv.animate({height: 'toggle'}, 500, function(){
if (type == 'expand')
theDiv.after('<p class="desc"><a href="#" class="dropdown" id="' + theId + '">[ Collapse Information... ]</a></p>');
else
theDiv.before('<p class="desc">' + vText + ' <a href="#" class="dropdown" id="' + theId + '">[ Read more... ]</p>');
if (theId == 'optMat' && type == 'expand')
{
var sVidWidth = $("#sampleVideo").width();
$("#sampleVideo").css({'height': (sVidWidth/1.5) + 'px'});
}
else if (theId == 'optMat' && type == 'collapse')
{
var iframe = $('#sampleVideo')[0];
var player = $f(iframe);
player.api('pause');
}
if (theId == 'reqMat' && type == 'expand')
{
handleBullets();
}
});
});
好了,所以这将下拉[ Read more... ]
文本,并把它变成一个[ Collapse Information... ]
字符串,将下面去正被实际内容扩大。但是,当我点击[ Collapse Information... ]
文本时,它不会折叠任何东西,而是会进入页面的顶部,因此具有href="#"
,但使用.on
应防止在应用event.preventDefault();
时发生这种情况。
正在使用jQuery库在这里找到:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
我的HTML的布局像这样,如果这甚至事项:
<h4>Header 1</h4>
<p class="desc">Brief description. <a href="#" id="reqMat" class="dropdown">[ Read more... ]</a></p>
<div style="display: none;">
<p>More information is in here...</p>
</div>
<h4>Header 2</h4>
<p class="desc">Brief description. <a href="#" id="optMat" class="dropdown">[ Read more... ]</a></p>
<div style="display: none;">
<p>More information is in here...</p>
</div>
我第一次点击它,它的工作原理,但第二时间,当显示[ Collapse Information... ]
它根本不工作。所以它不会自动附加到动态创建的<p class="desc"><a href="#" class="dropdown" id="' + theId + '">[ Collapse Information... ]</a></p>
。
为什么不呢?有什么我应该使用,而不是.on
?我知道.live
自jQuery 1.7以来不再使用。 .click
将无法正常工作,因为我已经试过了。还有什么其他选择?
[无法获取jQuery on()注册动态添加内容](http://stackoverflow.com/questions/9698936/unable-to-get-jquery-on-to-register-dynamically-added -content) –