Sea*_*yth 0 javascript comparison jquery
我真的很茫然.我有以下代码:
function AddHeightToBottom(footerHeight)
{
if ($('#myId1').length)
{
$('#myId1').height($('#myId1').height() + footerHeight);
}
console.log(('#myId2').length);
if ($('#myId2').length > 0)
{
var dHeight = $('#myId1').height();
var aHeight = $('.AF').height();
$('#myId1').height(dHeight + aHeight);
var newHeight = $('#myId1').height();
alert(newHeight);
}
else
{
alert('why?!??????');
}
}
Run Code Online (Sandbox Code Playgroud)
$('#myId2').长度是1,正如我所料.但是,当它进行比较时
if(1 > 0)
Run Code Online (Sandbox Code Playgroud)
它每天都在做事情,我不知道为什么.任何帮助,将不胜感激.
您正在使用jquery,因此请确保在document.ready中运行它:
$( document ).ready(function() {
if($('#element').length > 0) { //do thing 1 }
else { //do thing 2 }
});
Run Code Online (Sandbox Code Playgroud)
如果您在另一个函数中调用它,那么该函数必须出现在document.ready中.在文档"准备就绪"之前,无法安全地操作页面.jQuery为您检测这种准备状态.包含在$(document).ready()中的代码只有在页面文档对象模型(DOM)准备好执行JavaScript代码后才会运行.包含在$(window).load(function(){...})中的代码将在整个页面(图像或iframe)(而不仅仅是DOM)准备好后运行.*引自下面的链接.
https://learn.jquery.com/using-jquery-core/document-ready/
function AddHeightToBottom(footerHeight)
{
if ($('#myId1').length){
$('#myId1').height($('#myId1').height() + footerHeight);
}
console.log(('#myId2').length);
if ($('#myId2').length > 0)
{
alert("See, it works...");
var dHeight = $('#myId1').height();
var aHeight = $('.AF').height();
$('#myId1').height(dHeight + aHeight);
var newHeight = $('#myId1').height();
alert("New height: " + newHeight);
}
else
{
alert('why?!??????');
}
}
$( document ).ready(function() {
var footerHeight = 25;
AddHeightToBottom(footerHeight);
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myId1">div with id of myId1</div>
<br>
<div id="myId2">div with id of myId2</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |