Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

javascript - python django only the first statement statement can be accessed

i can acccess only the first statement in my name app

javascript:

<script type="text/javascript">
    function searched(){
    {% for names in name %}
        nameSearched = document.getElementById('name').value;
        document.getElementById('dis').innerHTML = nameSearched;
            if (nameSearched == "{{ names.First }}" ){
                document.getElementById('dis').innerHTML = "{{ names.Last }}";
            } else {
                document.getElementById('dis').innerHTML = "none";
            }
    {% endfor %}
    }
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is your function searched() in the script-tag.

If you have for example following name-instances:

[
    {
        'First': 'foo',
        'Last': 'bar',
    },
    {
        'First': 'foobar',
        'Last': 'barfoo',
    }
]

So your rendered if-else in the function would look like this:

function searched(){
    nameSearched = document.getElementById('name').value;
    if ("foo" == nameSearched) {
        ...
    } else {
        ...
    }
    if ("bar" == nameSearched) {
        ...
    } else {
        ...
    }
}

So as you can see, you are always running into the else if you entered foo.

What you could do is the following in your for-loop:

 <script type="text/javascript">
    function searched(){
      nameSearched = document.getElementById('name').value;
      {% for names in name %}
        {% if forloop.first %}
          if ("{{ names.First }}" == nameSearched) {
            document.getElementById('dis').innerHTML = "{{ names.Last }}";
          }
        {% else %}
          else if ("{{ names.First }}" == nameSearched) {
            document.getElementById('dis').innerHTML = "{{ names.Last }}";
          }
        {% endif %}
      {% endfor %}
      {% if name %}
        else {
          document.getElementById('dis').innerHTML = "none";
        }
      {% endif %}
    }
</script>

This would result in the following:

function searched(){
    nameSearched = document.getElementById('name').value;
    if ("foo" == nameSearched) {
        ...
    }
    else if ("foobar" == nameSearched) {
        ...
    }
    else {
        ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...