Ошибка JavaScript - Chrome говорят, что это не функция - PullRequest
0 голосов
/ 26 апреля 2018

У меня есть файл JS и HTML. Из HTML я вызываю функцию по клику.

Моя проблема - Спецификация_не работает, но Chrome выдает следующую ошибку:

Uncaught TypeError: spec_existing не является функцией

Так в чем же проблема? Почему не работает другая функция?

Вот мой код:

$( document ).ready(function() {

        if ($('#radio_specification_none').attr("checked")){

            $("#specification_existing_box").hide();    // hide existing_spec
            $("#specification_new_box").hide();         // hide new_spec

            $('#specification_existing_box')[0].selectedIndex = 0;          // set existing specifications to default value

            $('#specification_existing_box').prop('required', false);        // set existing spec. size the required attribute to false
            $('#specification_new_box').prop('required', false);        // set for new spec. the required attribute to false
        }
        if ($('#radio_specification_existing').attr("checked")){

            $("#specification_existing_box").show();            // hide existing_spec
            $("#specification_new_box").hide();                 // hide create new_spec

            $('#specification_existing_box').prop('required', true);        // set for new_spec the required attribute to true
            $('#specification_new_box').prop('required', false);            // set for new_spec the required attribute to false
        }
        if ($('#radio_specification_new').attr("checked")){

            $("#specification_new_box").show();                // show new_spec
            $("#specification_existing_box").hide();           // hide existing_spec

            $('#specification_existing_box')[0].selectedIndex = 0;          // set existing specifications to default value

            $('#specification_existing_box').prop('required', false);        // set for new_spec the required attribute to false
            $('#specification_new_box').prop('required', true);             // set for new_spec the required attribute to true
        }

    // ---- show and hide sizes ----- //

    // children sizes (default)
    $('#radio_child').change(function(){
        if (!$('#radio_child').checked){        // change if other user pick other button; this one is then false

            $("#child_sizes").show();           // show child sizes
            $("#konfektion_sizes").hide();      // hide adult sizes
        }

        $('#select_konfektion_sizes')[0].selectedIndex = 0;     // set adult size to "Wählen..."

        $('#select_child_sizes').prop('required',true);         // set for child size the required attribute to true
        $('#select_konfektion_sizes').prop('required',false);   // set for adult size the required attribute to false
    });
    // adult sizes
    $('#radio_adult').change(function(){        // change if other user pick other button; this one is then false
        if (!$('#radio_adult').checked){

            $("#child_sizes").hide();           // hide child sizes
            $("#konfektion_sizes").show();      // show adult sizes
        }

        $('#select_child_sizes')[0].selectedIndex = 0;          // set children size to default value

        $('#select_child_sizes').prop('required',false);        // set for child size the required attribute to false
        $('#select_konfektion_sizes').prop('required',true);    // set for adult size the required attribute to true
    });



    // triggers
    $('#radio_child').trigger('change');                        // trigger change (child radio) for one time, if document load

});

function specification_none(element){

		alert("specification_none");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_existing_box').prop('checked', "");
    $('#specification_new_box').prop('checked', "");

    //hide other specifications
    $("#specification_existing_box").hide();    // hide existing_spec
    $("#specification_new_box").hide();         // hide new_spec

    // set existing specifications to default value
    $('#specification_existing_box')[0].selectedIndex = 0;


    // set the required attribute from THIS input to true
    $('#specification_none_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_existing_box').prop('required', false);
    $('#specification_new_box').prop('required', false);
}

function specification_existing(element){

		alert("specification_existing");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_none_box').prop('checked', "");
    $('#specification_new_box').prop('checked', "");

    // show existing box
    $("#specification_existing_box").show();    // hide existing_spec

    //hide other specifications
    $("#specification_none_box").hide();    // hide existing_spec
    $("#specification_new_box").hide();         // hide new_spec

    // set the required attribute from THIS input to true
    $('#specification_existing_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_none_box').prop('required', false);
    $('#specification_new_box').prop('required', false);
}

function specification_new(element){

		alert("specification_new");

    // change the checked attribute
    $(element).prop('checked', "checked");
    $('#specification_existing_box').prop('checked', "");
    $('#specification_none_box').prop('checked', "");

    //hide other specifications
    $("#specification_existing_box").hide();    // hide existing_spec
    $("#specification_none_box").hide();         // hide new_spec

    // set existing specifications to default value
    $('#specification_existing_box')[0].selectedIndex = 0;


    // set the required attribute from THIS input to true
    $('#specification_new_box').prop('required', true);
    // set the required attribute from the other inputs to false
    $('#specification_existing_box').prop('required', false);
            $('#specification_none_box').prop('required', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<script type="text/javascript"  src="{{ url_for('static', filename='js/my.js') }}" ></script>

 <!--clothes specification-->
    <div class="raidio_box_specifications">
        <div>
            <table>
                <tr>
                <td><p>Besonderheit:  </p></td>
                <td  class="custom-control custom-radio custom-control-inline size_art_inner last_radio">
                    <input type="radio" id="radio_specification_new" name="specification" class="custom-control-input" onclick="specification_new(this)">
                    <label class="custom-control-label" for="radio_specification_new">neue erstellen</label>
                </td>
                <td class="custom-control custom-radio custom-control-inline size_art_inner">
                    <input type="radio" id="radio_specification_existing" name="specification" class="custom-control-input" onclick="specification_existing(this)" {% if clothing_info[0].clothes_specification_id != 1 %} checked="checked" {% else %}  {% endif %}>
                    <label class="custom-control-label" for="radio_specification_existing" >vorhandene</label>
                </td>
                <td class="custom-control custom-radio custom-control-inline size_art_inner">
                    <input type="radio" id="radio_specification_none" name="specification" class="custom-control-input" onclick="specification_none(this)" {% if clothing_info[0].clothes_specification_id == 1 %} checked="checked" {% else %}  {% endif %}>
                    <label class="custom-control-label" for="radio_specification_none">keine</label>
                </td>
                </tr>
            </table>
        </div>
    </div>

Может ли кто-нибудь помочь мне здесь

1 Ответ

0 голосов
/ 26 апреля 2018

Я не могу понять, почему это не работает. Я сделал работающую версию, и она отлично работает.

Но так как вы используете onclick реквизиты элементов HTML, здесь может быть что-то пошло не так. Поскольку вы используете jQuery, рассмотрите возможность привязки обратных вызовов с помощью метода jQuery .click() (см. Ниже).

Этот метод может значительно уменьшить количество ошибок, возникающих при определении области и т. Д., И вам не нужно загрязнять глобальное пространство JS.

Потенциально у вас есть какой-нибудь скрипт, который просто устанавливает функцию specification_existing на что-то еще, подобное этому:

specification_existing = 'accidentally changed specification_existing'

На это также указывает полученная вами ошибка:

  • ... is not a function указывает, что «переменная» существует, но не является вызываемой функцией

  • ... is not defined указывает, что «переменная», которую вы пытаетесь вызвать, неизвестна

Вот некоторые вещи, которые могут помочь вам решить такие проблемы:

  • Держите ваше глобальное пространство в чистоте. Выполните ваш код (function(){/* your code */})() или аналогичным образом.

  • всегда объявлять и инициализировать переменные (var myLocalVar) или использовать строгий режим

  • старайтесь не смешивать код JS с вашим HTML. Используйте JQuery или лучше Vanilla JS API: jQuery.on('click', ()=>{[...]}) element.addEventListener('click', ()=>{[...]})

$(function(){
  function specification_none(element) {
    console.log('specification_none')

      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_existing_box').prop('checked', "");
      $('#specification_new_box').prop('checked', "");

      //hide other specifications
      $("#specification_existing_box").hide(); // hide existing_spec
      $("#specification_new_box").hide(); // hide new_spec

      // set existing specifications to default value
      //$('#specification_existing_box')[0].selectedIndex = 0;


      // set the required attribute from THIS input to true
      $('#specification_none_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_existing_box').prop('required', false);
      $('#specification_new_box').prop('required', false);
  }

  function specification_existing(element) {
    console.log('specification_existing')
      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_none_box').prop('checked', "");
      $('#specification_new_box').prop('checked', "");

      // show existing box
      $("#specification_existing_box").show(); // hide existing_spec

      //hide other specifications
      $("#specification_none_box").hide(); // hide existing_spec
      $("#specification_new_box").hide(); // hide new_spec

      // set the required attribute from THIS input to true
      $('#specification_existing_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_none_box').prop('required', false);
      $('#specification_new_box').prop('required', false);
  }

  function specification_new(element) {
    console.log('specification_new')

      // change the checked attribute
      $(element).prop('checked', "checked");
      $('#specification_existing_box').prop('checked', "");
      $('#specification_none_box').prop('checked', "");

      //hide other specifications
      $("#specification_existing_box").hide(); // hide existing_spec
      $("#specification_none_box").hide(); // hide new_spec

      // set existing specifications to default value
      //$('#specification_existing_box')[0].selectedIndex = 0;


      // set the required attribute from THIS input to true
      $('#specification_new_box').prop('required', true);
      // set the required attribute from the other inputs to false
      $('#specification_existing_box').prop('required', false);
      $('#specification_none_box').prop('required', false);
  }

  $('#radio_specification_new').click(specification_new)
  $('#radio_specification_existing').click(specification_existing)
  $('#radio_specification_none').click(specification_none)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="raidio_box_specifications">
    <div>
        <table>
            <tr>
              <td>
                  <p>Besonderheit: </p>
              </td>
              <td class="custom-control custom-radio custom-control-inline size_art_inner last_radio">
                  <input type="radio" id="radio_specification_new" name="specification" class="custom-control-input">
                  <label class="custom-control-label" for="radio_specification_new">neue erstellen</label>
              </td>
              <td class="custom-control custom-radio custom-control-inline size_art_inner">
                  <input type="radio" id="radio_specification_existing" name="specification" class="custom-control-input" {% if clothing_info[0].clothes_specification_id !=1 %} checked="checked" {% else %} {% endif %}>
                  <label class="custom-control-label" for="radio_specification_existing">vorhandene</label>
              </td>
              <td class="custom-control custom-radio custom-control-inline size_art_inner">
                  <input type="radio" id="radio_specification_none" name="specification" class="custom-control-input" {% if clothing_info[0].clothes_specification_id==1 %} checked="checked" {% else %} {% endif %}>
                  <label class="custom-control-label" for="radio_specification_none">keine</label>
              </td>
            </tr>
        </table>
    </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...