简体   繁体   中英

What is the best solution for scrollWidth problem?

In Chrome console:

$('.table-responsive').width(); //working
$('.table-responsive')[0].scrollWidth; //working

In code while rendering HTML:

$('.table-responsive').width(); //working
$('.table-responsive')[0].scrollWidth; //not-working

Cannot read property 'scrollWidth' of undefined

If code works on browser's console ( aka dev tools ) and doesn't work withing your JS code, that means ( in most cases ) your JS code runs before DOM/HTML is actually loaded.

You have 2 options:

  1. Put your script tag on bottom of the page ( just before </body> )
  2. Use jQuery's .ready() , example:

$(document).ready(function(){ ... });

Which is equivalent to the recommended way of calling:

$(function() { ... });

Related helpful question, here on SO: What does $(function() {} ); do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM