Select2基本示例不起作用 [英] Select2 basic example not working

查看:138
本文介绍了Select2基本示例不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使select2库与symfony2脚本一起使用.

I am trying to get select2 library working with symfony2 script.

我正在尝试实现提供的基本示例 https://select2.github.io/examples.html 页面.

I am trying to implement basic example provided https://select2.github.io/examples.html page.

因此,我已添加到页面标题:

Thus I added to my page header:

<!-- SELECT 2-->
                            <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
                            <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
                            <!-- /SELECT2 -->

并遵循示例中提供的以下代码:

and following this code provided in example:

<script type="text/javascript">
     $(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>

<select id="appbundle_items_accountdebet" name="appbundle_items[accountdebet]" class="js-example-basic-single"><option value="1">001 - Środki trwałe x</option><option value="2">001-001 - Środek trwały 1 </option><option value="3">001-002 - Środek trwały 2 </option><option value="4">002 - Kasa</option><option value="7">04-33 - test</option><option value="10">05 - dff</option></select>

不幸的是,由于没有视觉变化,我似乎做错了什么.

Unluckily it seems that I am doing something wrong as no visual changes takes place.

整个页面代码:

<!-- app/Resources/views/base.html.php -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Accounting Book's Online</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->

        <link href="http://localhost/symfony_learn/web/bundles/bootstrap/css/bootstrap.css" rel="stylesheet">
    <style type="text/css">
      body {
        padding-top: 60px;
        padding-bottom: 40px;
      }
      .sidebar-nav {
        padding: 9px 0;
      }

      @media (max-width: 980px) {
        /* Enable use of floated navbar text */
        .navbar-text.pull-right {
          float: none;
          padding-left: 5px;
          padding-right: 5px;
        }
      }
    </style>


    <link href="http://localhost/symfony_learn/web/bundles/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/html5shiv.js"></script>
    <![endif]-->

    <!-- Fav and touch icons -->
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://localhost/symfony_learn/web/bundles/bootstrap/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://localhost/symfony_learn/web/bundles/bootstrap/ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://localhost/symfony_learn/web/bundles/bootstrap/ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="http://localhost/symfony_learn/web/bundles/bootstrap/ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="http://localhost/symfony_learn/web/bundles/bootstrap/ico/favicon.png">

                            <!-- SELECT 2-->
                            <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
                            <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
                            <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
                            <!-- /SELECT2 -->
  </head>

  <body>


<!-- Kod tymczasowy -->
<!-- /Kod tymczasowy -->

    <div class="navbar navbar-inverse navbar-top"> <!-- navbar-fixed-top -->
      <div class="navbar-inner">
        <div class="container-fluid">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="#">Accounting Book's Online</a>
          <div class="nav-collapse collapse">
            <p class="navbar-text pull-right">
                        <p>Username: Abdel</p>
                        </p>
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="/symfony_learn/web/app_dev.php/app/static/help">Help</a></li>
              <li><a href="/symfony_learn/web/app_dev.php/app/static/software">Software</a></li>
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span3">
          <div class="well sidebar-nav">
            <ul class="nav nav-list">
              <li class="nav-header">Actions</li>
              <li ><a href="/symfony_learn/web/app_dev.php/app/accounts/">Accounts</a></li>
              <li ><a href="/symfony_learn/web/app_dev.php/app/listbooks/">Books</a></li>
              <li ><a href="/symfony_learn/web/app_dev.php/app/documents/">Documents</a></li>
              <li class="nav-header">Reports</li>
              <li ><a href="/symfony_learn/web/app_dev.php/app/accounts/reportsums">Accounts values</a>
            </ul>
          </div><!--/.well -->
                   <div class="well sidebar-nav">
            <ul class="nav nav-list">
              <li class="nav-header">Name of entity</li>
              Test <A HREF="/symfony_learn/web/app_dev.php/app/listbooks/">[Change]</A>
              </ul>
              </div> <!--/.well -->


        </div><!--/span-->
        <div class="span9">
          <div class="hero-unit">
            <p>      <B>Item</B><BR>


<form name="appbundle_items" method="post" action="">
 <SCRIPT type="text/javascript">
     $(document).ready(function() {
$("js-example-basic-single").select2();
});
</SCRIPT>

<div id="appbundle_items"><div>                <label for="appbundle_items_marker" class="required">Marker</label><input type="text" id="appbundle_items_marker" name="appbundle_items[marker]" required="required" maxlength="220" /></div><div>                <label class="required">Itemdate</label><div id="appbundle_items_itemdate" maxlength="220"><select id="appbundle_items_itemdate_month" name="appbundle_items[itemdate][month]"><option value="1">Jan</option><option value="2">Feb</option><option value="3">Mar</option><option value="4">Apr</option><option value="5">May</option><option value="6">Jun</option><option value="7">Jul</option><option value="8">Aug</option><option value="9">Sep</option><option value="10">Oct</option><option value="11">Nov</option><option value="12">Dec</option></select><select id="appbundle_items_itemdate_day" name="appbundle_items[itemdate][day]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option></select><select id="appbundle_items_itemdate_year" name="appbundle_items[itemdate][year]"><option value="2010">2010</option><option value="2011">2011</option><option value="2012">2012</option><option value="2013">2013</option><option value="2014">2014</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option><option value="2019">2019</option><option value="2020">2020</option></select></div></div><div>                <label for="appbundle_items_itemvalue" class="required">Itemvalue</label><input type="text" id="appbundle_items_itemvalue" name="appbundle_items[itemvalue]" required="required" /></div><div>                <label for="appbundle_items_accountdebet" class="required">Accountdebet</label><select id="appbundle_items_accountdebet" name="appbundle_items[accountdebet]" class="js-example-basic-single"><option value="1">001 - Środki trwałe x</option><option value="2">001-001 - Środek trwały 1 </option><option value="3">001-002 - Środek trwały 2 </option><option value="4">002 - Kasa</option><option value="7">04-33 - test</option><option value="10">05 - dff</option></select></div><div>                <label for="appbundle_items_accountcredit" class="required">Accountcredit</label><select id="appbundle_items_accountcredit" name="appbundle_items[accountcredit]" class="js-example-basic-single"><option value="1">001 - Środki trwałe x</option><option value="2">001-001 - Środek trwały 1 </option><option value="3">001-002 - Środek trwały 2 </option><option value="4">002 - Kasa</option><option value="7">04-33 - test</option><option value="10">05 - dff</option></select></div><div><button type="submit" id="appbundle_items_save" name="appbundle_items[save]">Add item</button></div><input type="hidden" id="appbundle_items__token" name="appbundle_items[_token]" value="uc4gtvak7M-3gc4HsIuVlr0EpcycuctUGPJu_kAI7c8" /></div>
</form>

  </p>
          </div>

        </div><!--/span-->
      </div><!--/row-->

      <hr>

      <footer>
        <p>&copy; Investment Opportunities Sp. z o.o. 2015</p>
      </footer>

    </div><!--/.fluid-container-->

    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/jquery.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-transition.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-alert.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-modal.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-dropdown.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-scrollspy.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-tab.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-tooltip.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-popover.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-button.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-collapse.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-carousel.js"></script>
    <script src="http://localhost/symfony_learn/web/bundles/bootstrap/js/bootstrap-typeahead.js"></script>


<div id="sfwdt3909dd" class="sf-toolbar" style="display: none"></div><script>/*<![CDATA[*/    Sfjs = (function() {        "use strict";        var noop = function() {},            collectionToArray = function (collection) {                var length = collection.length || 0,                    results = new Array(length);                while (length--) {                    results[length] = collection[length];                }                return results;            },            profilerStorageKey = 'sf2/profiler/',            request = function(url, onSuccess, onError, payload, options) {                var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');                options = options || {};                options.maxTries = options.maxTries || 0;                xhr.open(options.method || 'GET', url, true);                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');                xhr.onreadystatechange = function(state) {                    if (4 !== xhr.readyState) {                        return null;                    }                    if (xhr.status == 404 && options.maxTries > 1) {                        setTimeout(function(){                            options.maxTries--;                            request(url, onSuccess, onError, payload, options);                        }, 500);                        return null;                    }                    if (200 === xhr.status) {                        (onSuccess || noop)(xhr);                    } else {                        (onError || noop)(xhr);                    }                };                xhr.send(payload || '');            },            hasClass = function(el, klass) {                return el.className && el.className.match(new RegExp('\\b' + klass + '\\b'));            },            removeClass = function(el, klass) {                if (el.className) {                    el.className = el.className.replace(new RegExp('\\b' + klass + '\\b'), ' ');                }            },            addClass = function(el, klass) {                if (!hasClass(el, klass)) {                    el.className += " " + klass;                }            },            getPreference = function(name) {                if (!window.localStorage) {                    return null;                }                return localStorage.getItem(profilerStorageKey + name);            },            setPreference = function(name, value) {                if (!window.localStorage) {                    return null;                }                localStorage.setItem(profilerStorageKey + name, value);            },            requestStack = [],            renderAjaxRequests = function() {                var requestCounter = document.querySelectorAll('.sf-toolbar-ajax-requests');                if (!requestCounter.length) {                    return;                }                var tbodies = document.querySelectorAll('.sf-toolbar-ajax-request-list');                var state = 'ok';                if (tbodies.length) {                    var tbody = tbodies[0];                    var rows = document.createDocumentFragment();                    if (requestStack.length) {                        for (var i = 0; i < requestStack.length; i++) {                            var request = requestStack[i];                            var row = document.createElement('tr');                            rows.appendChild(row);                            var methodCell = document.createElement('td');                            methodCell.textContent = request.method;                            row.appendChild(methodCell);                            var pathCell = document.createElement('td');                            pathCell.className = 'sf-ajax-request-url';                            pathCell.textContent = request.url;                            pathCell.setAttribute('title', request.url);                            row.appendChild(pathCell);                            var durationCell = document.createElement('td');                            durationCell.className = 'sf-ajax-request-duration';                            if (request.duration) {                                durationCell.textContent = request.duration + "ms";                            } else {                                durationCell.textContent = '-';                            }                            row.appendChild(durationCell);                            row.appendChild(document.createTextNode(' '));                            var profilerCell = document.createElement('td');                            if (request.profilerUrl) {                                var profilerLink = document.createElement('a');                                profilerLink.setAttribute('href', request.profilerUrl);                                profilerLink.textContent = request.profile;                                profilerCell.appendChild(profilerLink);                            } else {                                profilerCell.textContent = 'n/a';                            }                            row.appendChild(profilerCell);                            var requestState = 'ok';                            if (request.error) {                                requestState = 'error';                                if (state != "loading" && i > requestStack.length - 4) {                                    state = 'error';                                }                            } else if (request.loading) {                                requestState = 'loading';                                state = 'loading';                            }                            row.className = 'sf-ajax-request sf-ajax-request-' + requestState;                        }                        var infoSpan = document.querySelectorAll(".sf-toolbar-ajax-info")[0];                        var children = collectionToArray(tbody.children);                        for (var i = 0; i < children.length; i++) {                            tbody.removeChild(children[i]);                        }                        tbody.appendChild(rows);                        if (infoSpan) {                            var text = requestStack.length + ' call' + (requestStack.length > 1 ? 's' : '');                            infoSpan.textContent = text;                        }                    } else {                        var cell = document.createElement('td');                        cell.setAttribute('colspan', '4');                        cell.textContent = "No AJAX requests yet.";                        var row = document.createElement('tr');                        row.appendChild(cell);                        tbody.appendChild(row);                    }                }                requestCounter[0].textContent = requestStack.length;                var className = 'sf-toolbar-ajax-requests sf-toolbar-status';                if (state == 'ok') {                    className += ' sf-toolbar-status-green';                } else if (state == 'error') {                    className += ' sf-toolbar-status-red';                } else {                    className += ' sf-ajax-request-loading';                }                requestCounter[0].className = className;            };        var addEventListener;        var el = document.createElement('div');        if (!'addEventListener' in el) {            addEventListener = function (element, eventName, callback) {                element.attachEvent('on' + eventName, callback);            };        } else {            addEventListener = function (element, eventName, callback) {                element.addEventListener(eventName, callback, false);            };        }                    if (window.XMLHttpRequest && XMLHttpRequest.prototype.addEventListener) {                var proxied = XMLHttpRequest.prototype.open;                XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {                    var self = this;                    /* prevent logging AJAX calls to static and inline files, like templates */                    var path = url;                    if (url.substr(0, 1) === '/') {                        if (0 === url.indexOf('\x2Fsymfony_learn\x2Fweb')) {                            path = url.substr(18);                        }                    }                    else if (0 === url.indexOf('http\x3A\x2F\x2Flocalhost\x2Fsymfony_learn\x2Fweb')) {                        path = url.substr(34);                    }                    if (path.substr(0, 1) === '/' && !path.match(new RegExp("^\/(app(_[\\w]+)?\\.php\/)?_wdt"))) {                        var stackElement = {                            loading: true,                            error: false,                            url: url,                            method: method,                            start: new Date()                        };                        requestStack.push(stackElement);                        this.addEventListener('readystatechange', function() {                            if (self.readyState == 4) {                                stackElement.duration = new Date() - stackElement.start;                                stackElement.loading = false;                                stackElement.error = self.status < 200 || self.status >= 400;                                stackElement.profile = self.getResponseHeader("X-Debug-Token");                                stackElement.profilerUrl = self.getResponseHeader("X-Debug-Token-Link");                                Sfjs.renderAjaxRequests();                            }                        }, false);                        Sfjs.renderAjaxRequests();                    }                    proxied.apply(this, Array.prototype.slice.call(arguments));                };            }                return {            hasClass: hasClass,            removeClass: removeClass,            addClass: addClass,            getPreference: getPreference,            setPreference: setPreference,            addEventListener: addEventListener,            request: request,            renderAjaxRequests: renderAjaxRequests,            load: function(selector, url, onSuccess, onError, options) {                var el = document.getElementById(selector);                if (el && el.getAttribute('data-sfurl') !== url) {                    request(                        url,                        function(xhr) {                            el.innerHTML = xhr.responseText;                            el.setAttribute('data-sfurl', url);                            removeClass(el, 'loading');                            (onSuccess || noop)(xhr, el);                        },                        function(xhr) { (onError || noop)(xhr, el); },                        '',                        options                    );                }                return this;            },            toggle: function(selector, elOn, elOff) {                var tmp = elOn.style.display,                    el = document.getElementById(selector);                elOn.style.display = elOff.style.display;                elOff.style.display = tmp;                if (el) {                    el.style.display = 'none' === tmp ? 'none' : 'block';                }                return this;            }        }    })();/*]]>*/</script><script>/*<![CDATA[*/    (function () {                Sfjs.load(            'sfwdt3909dd',            '/symfony_learn/web/app_dev.php/_wdt/3909dd',            function(xhr, el) {                el.style.display = -1 !== xhr.responseText.indexOf('sf-toolbarreset') ? 'block' : 'none';                if (el.style.display == 'none') {                    return;                }                if (Sfjs.getPreference('toolbar/displayState') == 'none') {                    document.getElementById('sfToolbarMainContent-3909dd').style.display = 'none';                    document.getElementById('sfToolbarClearer-3909dd').style.display = 'none';                    document.getElementById('sfMiniToolbar-3909dd').style.display = 'block';                } else {                    document.getElementById('sfToolbarMainContent-3909dd').style.display = 'block';                    document.getElementById('sfToolbarClearer-3909dd').style.display = 'block';                    document.getElementById('sfMiniToolbar-3909dd').style.display = 'none';                }                Sfjs.renderAjaxRequests();                /* Handle toolbar-info position */                var toolbarBlocks = document.querySelectorAll('.sf-toolbar-block');                for (var i = 0; i < toolbarBlocks.length; i += 1) {                    toolbarBlocks[i].onmouseover = function () {                        var toolbarInfo = this.querySelectorAll('.sf-toolbar-info')[0];                        var pageWidth = document.body.clientWidth;                        var elementWidth = toolbarInfo.offsetWidth;                        var leftValue = (elementWidth + this.offsetLeft) - pageWidth;                        var rightValue = (elementWidth + (pageWidth - this.offsetLeft)) - pageWidth;                        /* Reset right and left value, useful on window resize */                        toolbarInfo.style.right = '';                        toolbarInfo.style.left = '';                        if (leftValue > 0 && rightValue > 0) {                            toolbarInfo.style.right = (rightValue * -1) + 'px';                        } else if (leftValue < 0) {                            toolbarInfo.style.left = 0;                        } else {                            toolbarInfo.style.right = '-1px';                        }                    };                }            },            function(xhr) {                if (xhr.status !== 0) {                    confirm('An error occurred while loading the web debug toolbar (' + xhr.status + ': ' + xhr.statusText + ').\n\nDo you want to open the profiler?') && (window.location = '/symfony_learn/web/app_dev.php/_profiler/3909dd');                }            },            {'maxTries': 5}        );    })();/*]]>*/</script>
</body>
</html>

推荐答案

在完整的代码示例中,通过添加"来修复类选择器.在班级名称前,更改:

in your full code example, fix class selector by adding "." in front of class name, change:

 <SCRIPT type="text/javascript">
     $(document).ready(function() {
$("js-example-basic-single").select2();
});
</SCRIPT>

收件人:

<script type="text/javascript">
     $(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>

  1. 在dom准备好代码之前,您是否在页面上包含了jquery?

  1. have you included jquery on your page before dom ready code?

为我们提供JS控制台日志

provide us with JS console log

使用js调试器检查解析器是否到达:

check with js debugger if parser reaches:

$(.js-example-basic-single").select2();

$(".js-example-basic-single").select2();

您的代码至少在这里似乎可以正常工作: http://jsfiddle.net/8349tck1/

your code seems to work just fine at least here: http://jsfiddle.net/8349tck1/

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

<select id="appbundle_items_accountdebet" name="appbundle_items[accountdebet]" class="js-example-basic-single"><option value="1">001 - Środki trwałe x</option><option value="2">001-001 - Środek trwały 1 </option><option value="3">001-002 - Środek trwały 2 </option><option value="4">002 - Kasa</option><option value="7">04-33 - test</option><option value="10">05 - dff</option></select>

<script>
    $(document).ready(function() {
    $(".js-example-basic-single").select2();
});
</script>

这篇关于Select2基本示例不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆