用于在JS函数中的变量之间切换的单选按钮

时间:2017-08-20 13:13:05

标签: javascript jquery

我有2个选项(相同的api请求,不同的网址)我想使用切换按钮(Radio)让用户选择结果的类型:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.swing.*;

@SuppressWarnings("serial")
public class SwingWorkerExample extends JPanel {
    private JTextArea textArea = new JTextArea(30, 40);
    private MyWorker myWorker;

    public SwingWorkerExample() {
        textArea.setFocusable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JButton(new AbstractAction("Start Worker") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (myWorker != null && !myWorker.isDone()) {
                    myWorker.setLoopRunning(false);
                }

                myWorker = new MyWorker();
                myWorker.execute();
            }
        }));
        bottomPanel.add(new JButton(new AbstractAction("Stop Worker") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (myWorker != null && !myWorker.isDone()) {
                    myWorker.setLoopRunning(false);
                }
            }
        }));

        setLayout(new BorderLayout());
        add(scrollPane);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    private class MyWorker extends SwingWorker<Void, String> {
        private volatile boolean loopRunning = true;

        @Override
        protected Void doInBackground() throws Exception {
            for (int j = 0; j < 1000 && loopRunning; j++) {
                for (int i = 0; i < 1000 && loopRunning; i++) {
                    String text = String.format("My Text %03d", i);
                    publish(text);
                    TimeUnit.MILLISECONDS.sleep(10);
                }
            }
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            for (String text : chunks) {
                textArea.append(text + "\n");
            }
        }

        @Override
        protected void done() {
            textArea.append("Done\n");

            try {
                get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        public void setLoopRunning(boolean running) {
            this.loopRunning = running;
        }

        public boolean isLoopRunning() {
            return loopRunning;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        SwingWorkerExample mainPanel = new SwingWorkerExample();
        JFrame frame = new JFrame("SwingWorkerExample");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

HTML

function ApiRequest() {

var mydata = document.getElementById('userinput').value;
var userapi = document.getElementById('userapi').value; 
var userurl = document.getElementById('userurl').value; 


$.post(
  myurl,
    JSON.stringify({
      'api_key': userapi,
      'data': mydata,
    })).then(function(sent) { 
      var s = sent
      var obj = JSON.parse(s)
      $('.score').text("Score : " + obj.results*100)
      });
}

我应该使用这样的东西吗?

<input class="search-field" type="text" placeholder="I love writing code!" id="userinput">

<input class="search-field" type="text" placeholder="1234567890" id="userapi">


  <div class="material-switch pull-right" style="padding-left: 25px">
     <input id="userurl" name="hq" type="checkbox"/>
     <label for="userurl" class="label-success"></label>
  </div>

<button class="search" onclick="ApiRequest()">Try It</button>

1 个答案:

答案 0 :(得分:1)

确切地说,做一些你在问题中指出的类似事情。

带有用于选择网址的单选按钮的HTML可能是这样的:

<input type="radio" id="api-url-1" name="api-url" value="my-api-url-1">
<input type="radio" id="api-url-2" name="api-url" value="my-api-url-2">

获取已检查输入的值:

var radios = document.getElementsByName('api-url');
var chosenURL;
for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        chosenURL = radios[i].value;
        // you can break because just one radio can be selected
        break;
    }
}

<强> P.S。使用jQuery可以简单地替换所有这个块:

var chosenURL = $('input[name="api-url"]:checked').val();

然后使用动态网址启动请求:

$.post(
  chosenURL,
    JSON.stringify({
      'api_key': userapi,
      'data': mydata,
    })).then(function(sent) { 
      var s = sent
      var obj = JSON.parse(s)
      $('.score').text("Score : " + obj.results*100)
      });
}

摘录示例:

&#13;
&#13;
function trigger() {
  var chosenURL = $('input[name="api-url"]:checked').val();
  alert(chosenURL);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="api-url-1" name="api-url" value="my-api-url-1">API URL 1
<input type="radio" id="api-url-2" name="api-url" value="my-api-url-2">API URL 2
<button onclick="trigger()">Trigger</button>
&#13;
&#13;
&#13;