javascript - jQuery addClass/removeClass(无法读取未定义的属性 'length')

标签 javascript jquery html css

当我加载我的页面时,我希望我的一些 div 从一开始就被隐藏并且只显示一个,所以这是我为此找到的脚本。

<script>
    $(document).ready(function () {
        $(".total").click(function () {
            $("#piechart").removeClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".squat").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").removeClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".benchpress").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").removeClass('hidden');
            $("#piechartD").addClass('hidden');
        });
        $(".deadlift").click(function () {
            $("#piechart").addClass('hidden');
            $("#piechartS").addClass('hidden');
            $("#piechartB").addClass('hidden');
            $("#piechartD").removeClass('hidden');
        });
    });
</script>

这些是div

<div id="piechart" class="repPieChart"></div>                
<div id="piechartS" class="repPieChart hidden"></div>
<div id="piechartB" class="repPieChart hidden"></div>
<div id="piechartD" class="repPieChart hidden"></div>

CSS

.hidden {
    display: none;
}
.repPieChart {
    width: 100%;
    height: 500px;
    border-bottom: 5px solid #898989;
}

所以想法是第一个 div 从一开始就没有 hidden 类,所以它是可见的而其他的是隐藏的,然后当我点击链接到这个点击事件的标签时它会删除隐藏类或将隐藏类添加到正确的 div,它确实如此,我检查了 chrome 代码检查器,类被删除并以正确的方式添加,但是只有第一个 div 是可见的,当我点击显示另一个我得到标题中的错误。

有什么问题吗?

@{
Layout = "~/_SiteLayout.cshtml";
// Browser tab title.
Page.Title = "Repetitions";
// Opens connection to the database.
var db = Database.Open("SmallBakery");
// Gets the text typed into the textboxes and stores it in these variables.
var inputDate = Request.Form["inputDate"];
var endDate = Request.Form["endDate"];

var normOrAvg = Request.Form["NormOrAvg"];
// If no start date is selected, this will be used as the start date aka `inputDate`.
DateTime noStartDate = new DateTime(2000, 01, 01);
// If no end date is selected, this will be used as the end date.
DateTime noEndDate = DateTime.Now;

// If user does not choose eiter/any start/end date
// this will end up showing all results from `noStartDate` to todays date.
if (inputDate == "")
{
    inputDate = noStartDate.ToString("MMM d, yyyy");
}
if (endDate == "")
{
    endDate = noEndDate.ToString("MMM d, yyyy");
}
}

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        $(function () {

            // Get Date from datepicker
            var date = $(".datepicker").datepicker({ dateFormat: "M d, yy", showButtonPanel: true }).val

            // Use the date to create a Moment Object and format it so that it can be
            // used within the databse
            var databaseDate = moment(date).format('YY-MM-DD');

            // Use your correctly formatted date however you want, in this example
            // we are just console logging it to take a look if it's correctly parsed.
            console.log(databaseDate);

        });



    </script>
    <script>
        $(document).ready(function () {
            $('.holdLiftMenu li a').on('click', function () {
                $('li a.current').removeClass('current');
                $(this).addClass('current');
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            var elems = ['#piechart', '#piechartS', '#piechartB', '#piechartD']
            function show(item) {
                for (var i = 0; i < elems.length; i++) {
                    if (elems[i] === item) {
                        $(elems[i]).show();
                    } else {
                        $(elems[i]).hide()
                    }
                }
            }
            $(".total").click(function () {

                show("#piechart");
            });
            $(".squat").click(function () {
                show("#piechartS");
            });
            $(".benchpress").click(function () {
                show("#piechartB");
            });
            $(".deadlift").click(function () {

                show('');
            });
        });
    </script>
    <title></title>
</head>
<body>
    @{ 
        // DateTime variable for the startdate textbox placeholder.
        DateTime placeholderStartDate = Convert.ToDateTime(noStartDate);

        <h1 class="metricsTitle"><a href="~/metrics/">Repetitions in Intensity</a></h1>
        <p class="blackColor">Analyze in what range of intensity you accumulate most of your repetitions.</p>

        // Form with date textboxes and submit button.
        <form method="post" action="~/AJAXcalls/repinintAJAX.cshtml" name="form">
            <div class="reportDateDiv">

                <a class="blackColor fSize18 RPtxt">Reporting Period</a>

                <input type="text" name="inputDate" spellcheck="false" class="datepicker metricDateTextbox capitalFirst"
                      onchange="mySubmit(this.form)" value="@inputDate" autocomplete="off" placeholder="@placeholderStartDate.ToString("MMM d, yyyy")" readonly="readonly" />

                <a class="blackColor fSize16 RPtxtTo">to</a>

                <input type="text" name="endDate" spellcheck="false" class="datepicker metricDateTextbox capitalFirst"
                      onchange="mySubmit(this.form)" value="@endDate" autocomplete="off" placeholder="@noEndDate.ToString("MMM d, yyyy")" readonly="readonly" />

                <select name="NormOrAvg" class="dwmViewSelect" onchange="mySubmit(this.form)">
                    <option selected=@(Request.Form["NormOrAvg"] == "1") value="1">Rep Per Set</option>
                    <option selected=@(Request.Form["NormOrAvg"] == "2") value="2">Average Rep Per Set</option>
                </select>
                </div>
        </form>

        <div class="holdLiftMenu">
            <ul class="holdLiftMenuUL">
                <li class="holdLiftMenuLI"><a class="holdLiftMenuA total current">Total</a></li>
                <li class="holdLiftMenuLI"><a class="holdLiftMenuA squat">Squat</a></li>
                <li class="holdLiftMenuLI"><a class="holdLiftMenuA benchpress">Benchpress</a></li>
                <li class="holdLiftMenuLI"><a class="holdLiftMenuA deadlift">Deadlift</a></li>
            </ul>
        </div>

        // This div is updated with the data that is recieved from the background with the ajax information.
        <div id="here"></div>

        // Ajax script.
        <script type="text/javascript">
            function mySubmit(theForm) {
                $.ajax({ // create an AJAX call...
                    data: $(theForm).serialize(), // get the form data
                    type: $(theForm).attr('method'), // GET or POST
                    url: $(theForm).attr('action'), // the file to call
                    success: function (response) { // on success..
                        $('#here').html(response); // update the DIV
                    }

                });
            }
        </script>
    }
</body>

最佳答案

我做了一个fiddle , 期望它有效:

    $(document).ready(function () {
    var elems = ['#piechart', '#piechartS', '#piechartB', '#piechartD'];
show('');
    function show(item) {
        for(var i =0; i<elems.length;i++){
        if(elems[i]===item){
            $(elems[i]).show();
        }else{
        $(elems[i]).hide()
        }
      }
    }
            $(".total").click(function () {

                show("#piechart");
            });
            $(".squat").click(function () {
            show("#piechartS");
            });
            $(".benchpress").click(function () {
            show("#piechartB");
            });
            $(".deadlift").click(function () {

               show('');
            });
        });

已编辑,可以正常工作并在开始时隐藏

关于javascript - jQuery addClass/removeClass(无法读取未定义的属性 'length'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42378137/

相关文章:

javascript - QuotaExceededError : Dom exception 22: An attempt was made to add something to storage that exceeded the quota

javascript - 2 列网格布局与砌体

c# - ajax 调用后返回 View

javascript - 比较 Mongo 中的两个引用?

c# - 使用 System.Web.Optimization Bundling 最小化时,有没有办法禁用 js/css 验证?

javascript - 如何迭代 DataTables 2.1 中的对象数组

php - 使用 xpath 选择 css 类

html - 如何使表格标题的高度彼此不同?

javascript - 所有函数语句完成后的 typescript 调用语句

javascript - Charts.js 将 Canvas 宽度/高度设置为 0 并且不显示任何内容