Javascript在两个div内获取选择值

时间:2019-04-30 12:44:45

标签: javascript html

在我的项目中,我有一个封装到两个div中的选择,我必须从javascript的选择中获取文本或值。

              <RNCamera
                    ref={ref => {
                        this.camera = ref;
                    }}
                    style={styles.preview}
                    type={RNCamera.Constants.Type.back}
                    flashMode={RNCamera.Constants.FlashMode.on}
                    androidCameraPermissionOptions={{
                        title: 'Permission to use camera',
                        message: 'We need your permission to use your camera',
                        buttonPositive: 'Ok',
                        buttonNegative: 'Cancel',
                    }}
                    androidRecordAudioPermissionOptions={{
                        title: 'Permission to use audio recording',
                        message: 'We need your permission to use your audio',
                        buttonPositive: 'Ok',
                        buttonNegative: 'Cancel',
                    }}
                    onGoogleVisionBarcodesDetected={({ barcodes }) => {
                        console.log(barcodes);
                    }}
                />

我尝试以下代码:

<div class="col-lg-3 col-xs-6" id="div1">
      <div class="form-group" id="divTtype">
          <label>Templte Type:</label>
          <select class="form-control" id="ftype">
              <option value="..All">..All</option>
              <option value="Functional">Functional</option>
              <option value="Non Functional">Non Functional</option>
          </select>
        </div>
 </div>

但是当我尝试时:

function GetElementInsideContainer(containerID, childID) {
    var elm = document.getElementById(childID);
    var parent = elm ? elm.parentNode : {};
    return (parent.id && parent.id === containerID) ? elm : {};
}

一个“未定义”的回复给我。

我如何获得我选择的值?

非常感谢

7 个答案:

答案 0 :(得分:2)

实际上,您的HTML代码“ divTtype”中有一个错字,您打算编写divType

<div class="col-lg-3 col-xs-6" id="div1">
    <div class="form-group" id="divType">
        <label>Templte Type:</label>
        <select class="form-control" id="ftype">
            <option value="..All">..All</option>
            <option value="Functional">Functional</option>
            <option value="Non Functional">Non Functional</option>
        </select>
    </div>
</div>

此外,您需要使用textContent属性而不是text

最后请使用"id"调用该函数,否则您将调用未定义的变量divTypeftype

console.log(GetElementInsideContainer("divType", "ftype"));

这当然可以解决您当前的问题,尽管请参考拉斐尔的答案以寻求更好的方法。

答案 1 :(得分:1)

因为HTMLElement中不存在文本。 您必须这样做:

A::type

这里是documentation

答案 2 :(得分:1)

在将字符串作为参数发送时,应使用引号:

GetElementInsideContainer('divType', 'ftype').text;

答案 3 :(得分:1)

就像克里希纳(Krishna)在上述评论中所说,您应该能够这样做:

var select = document.getElementById('ftype')
var val = select.options[select.selectedIndex].value

您不必引用父节点。

答案 4 :(得分:1)

  

使用 textContent 并以 string 的形式传递ID,否则将其作为变量

     

其次,您具有id divTtype ,并且正在传递 divType

import time
from bs4 import BeautifulSoup as soup
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

# The path to where you have your chrome webdriver stored:
webdriver_path = '/Users/rawlins/Downloads/chromedriver'

# Add arguments telling Selenium to not actually open a window
chrome_options = Options()
chrome_options.add_argument('--headless')
#chrome_options.add_argument('--window-size=1920x1080')

# Fire up the headless browser
browser = webdriver.Chrome(executable_path = webdriver_path,
chrome_options = chrome_options)

# Load webpage
url = "https://cnx.org/search?q=subject:Arts"
browser.get(url)

# to ensure that the page has loaded completely.
time.sleep(3)

data = [] 
n = 2
for i in range(1, n+1):
    if (i == 1):
        # handle first page
        response = requests.get(url)
    response = requests.get(url + "&page=" + str(i))
    #response = requests.get(url + "&page=" + str(i),headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})

    # Parse HTML, close browser
    page_soup = soup(browser.page_source, 'lxml')
    containers = page_soup.findAll("tr")
    browser.quit()

    for container in containers:
        item = {}
        item['type'] = "Course Material"
        if container.find('td', {'class' : 'title'}):
            item['title'] = container.find('td', {'class' : 'title'}).h4.text.strip()
        else:
            item['title'] = ""
        if container.find('td', {'class' : 'authors'}):
            item['author'] = container.find('td', {'class' : 'authors'}).text.strip()
        else:
            item['author'] = ""
        if container.find('td', {'class' : 'title'}):
            item['link'] = "https://cnx.org/" + container.find('td', {'class' : 'title'}).a["href"]
        else: 
            item['link'] = ""
        if container.find('td', {'class' : 'title'}):
            item['description'] = container.find('td', {'class' : 'title'}).span.text
        else: 
            item['description'] = ""
        item['subject'] = "Arts"
        item['source'] = "OpenStax CNX"
        item['base_url'] = "https://cnx.org/browse"
        item['license'] = "Attribution"
        data.append(item) # add the item to the list

    with open("js-webscrape.json", "w") as writeJSON:
        json.dump(data, writeJSON, ensure_ascii=False)
function GetElementInsideContainer(containerID, childID) {
  var elm = document.getElementById(childID);
  var parent = elm ? elm.parentNode : {};
  return (parent.id && parent.id === containerID) ? elm : {};
}


var a = GetElementInsideContainer("divType", "ftype").textContent;
console.log(a)

答案 5 :(得分:1)

似乎在这里工作正常。

<div class="col-lg-3 col-xs-6" id="div1">
      <div class="form-group" id="divTtype">
          <label>Templte Type:</label>
          <select class="form-control" id="ftype">
              <option value="..All">..All</option>
              <option value="Functional">Functional</option>
              <option value="Non Functional">Non Functional</option>
          </select>
        </div>
 </div>
 <button onclick="getSelected(GetElementInsideContainer('divTtype', 'ftype'))">Get Selected Value</button>
 <script>
 function getSelected(objEl)
 {
 	alert(objEl.options[objEl.selectedIndex].text);
 }
 
function GetElementInsideContainer(containerID, childID) {
    var elm = document.getElementById(childID);
    var parent = elm ? elm.parentNode : {};
    return (parent.id && parent.id === containerID) ? elm : {};
}
 </script>

答案 6 :(得分:1)

您需要选择的选择值吗?

我做了那段代码并获得了所选内容的HTML。 使用此代码段,您可以获得select的值

<div class="col-lg-3 col-xs-6" id="div1">
      <div class="form-group" id="divTtype">
          <label>Templte Type:</label>
          <select class="form-control" id="ftype">
              <option value="..All">..All</option>
              <option value="Functional">Functional</option>
              <option value="Non Functional">Non Functional</option>
          </select>
        </div>
 </div>
function GetElementInsideContainer( childID) {
    var elm = document.getElementById(childID);
    console.log(elm.value)
    return elm.value;
}
GetElementInsideContainer('ftype');

我认为您可能在参数中输入了错误的ID