Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 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 Reply

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 {
        ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...