如何在点击[JS]时获取元素ID

时间:2019-07-07 11:49:00

标签: javascript html css

我需要将按钮与div的ID连接起来,现在它们仅连接到类上。

function addClass(e) {
  // to get the correct effect
  effect = e.target.getAttribute('data-effect');
  // adding the effects
  menu.classList.toggle(effect);
  menu.classList.toggle('st-menu-open');

  // console.log(e.target.getAttribute('data-effect'));
}

完整代码: https://jsfiddle.net/eb26904s/

我想要实现的目标:

  • 菜单1-用id =“ menu1”打开div
  • 菜单2-使用id =“ menu2”打开div
  • 单击任意位置-关闭菜单

现在他们两个都以“ cv”类打开菜单。

2 个答案:

答案 0 :(得分:1)

当您单击.click时,同时显示uicv,但是您只能看到cv,因为它在ui上方。我建议在启动时同时隐藏两者,并在单击菜单时显示一个。

这是基于您的代码的演示:

var click = document.querySelectorAll('.click');
var st_menu = document.querySelectorAll('.st-menu');
var menu = document.querySelector('#st-container');
var effect;

for (var i = 0; i < click.length; i++) {
  click[i].addEventListener('click', addClass)
}


function addClass(e) {
  // to get the correct effect
  effect = e.target.getAttribute('data-effect');
  for (var i = 0; i < st_menu.length; i++) {
    st_menu[i].classList.remove("d-block");
  }
  var target_id = e.target.getAttribute('data-target');
  var target = document.getElementById(target_id);
  target.classList.toggle("d-block");
  // adding the effects
  menu.classList.toggle(effect);
  menu.classList.toggle('st-menu-open');
}
.ui {
  display: none;
  background: #215DD1;
  color: #fff;
}

.cv {
  display: none;
  background: #FF9F2F;
  color: #fff;
}

.cv.d-block, .ui.d-block {
  display: block;
}

.st-container {
	position: relative;
	overflow: hidden;
}

.st-menu {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
	visibility: hidden;
	width: 300px;
	height: 100%;
	-webkit-transition: all 0.5s;
	transition: all 0.5s;
}

.st-effect-1.st-menu {
	visibility: visible;
	-webkit-transform: translate3d(-100%, 0, 0);
	transform: translate3d(-100%, 0, 0);
}

.st-effect-1.st-menu-open .st-effect-1.st-menu {
	visibility: visible;
	-webkit-transform: translate3d(0, 0, 0);
	transform: translate3d(0, 0, 0);
}

.st-effect-1.st-menu::after {
	display: none;
}

body {
	background: #444;
	color: #48a770;
}
<div id="st-container">

  <div class="ui st-menu st-effect-1" id="menu1">
  </div>
  
  <div class="cv st-menu st-effect-1" id="menu2">
  </div>
  
  <div class="click" style="position: relative; left: 50%;" data-effect="st-effect-1" data-target="menu1">Menu1</div> 
  
   <div class="click" style="position: relative; left: 50%;" data-effect="st-effect-1" data-target="menu2">Menu2</div> 
  
  </div>

答案 1 :(得分:0)

使用事件委托更加简单。

import os
import sys
import pickle
import getpass
from subprocess import Popen, PIPE, call

python_path = r'C:\Users\{}\Documents\py_config.pkl'.format(getpass.getuser())

if sys.version_info.major < 3:
    check_path = os.path.exists(python_path)
    if check_path is False:
        while True:
            sys.stdout.write('Python 2.x is not supported do you have Python 3.x? [y/n]')
            answer = raw_input()
            sys.stdout.write("\r")
            if answer.lower() not in ['y', 'n', 'yes', 'no']:
                sys.stdout.write("Answer can be y or n. Try again..\n")
                continue
            break

        if answer.lower() in ['y', 'yes']:
            py_versions = {}
            sys.stdout.write('\nSelect Python3 version to use\n')
            p = Popen(['py', '--list'], stdout=PIPE)
            while True:
                line = p.stdout.readline()
                if not line:
                    break
                line = line.strip().strip('-')
                if line.startswith('3'):
                    line = line[:line.find('-')]
                    py_versions.update({len(py_versions): line})
            if not py_versions:
                sys.stdout.write('\nInstall Python 3 to be able to use this framework')
                exit()
            while True:
                options = ""
                for k, v in py_versions.items():
                    options += "[%s] %s\n" % (k,v)
                sys.stdout.write(options)
                answer = raw_input()
                if answer.isdigit() is False:
                    sys.stdout.write("\n Option must be numeric value. Please try again...\n")
                    continue

                selected_option = int(answer)
                if selected_option not in py_versions.keys():
                    sys.stdout.write("\n Option you entered does not exist. Please try again...\n")
                    continue

                py_version = py_versions.get(selected_option)
                if py_version is not None:
                    py_data = {'version': py_version}
                    sys.stdout.write('\nSelected Python version is %s\n' % py_version)
                    sys.stdout.write('\nChecking paths for this Python pleas wait..\n')
                    p = Popen(
                        'py -%s -c "import sys; import os; sys.stdout.write(os.path.dirname(sys.executable))" ' % py_version,
                        stdout=PIPE)
                    lines = p.stdout.readlines()
                    main_path = lines[0]

                    pycon_path = os.path.join(main_path,'Scripts','my_script.py')
                    if os.path.exists(pycon_path) is False:
                        sys.stdout.write("\n Can't locate my_script.py at {0} \n make sure you are using python "
                                         "version where you installed this package then try again...".format(pycon_path))
                        exit()

                    command = 'py -{0} {1}'.format(py_version, pycon_path)
                    py_data.update({'cmd': command})
                    with open(python_path, 'wb') as fw:
                        pickle.dump(py_data, fw)
                    call(command)

                break


        else:
            sys.stdout.write('\nInstall Python 3 to be able to use this framework')
    else:

        with open(python_path, 'rb') as fr:
            data = pickle.load(fr)
            version = data.get('version')
            sys.stdout.write('\nPython version is defined in %s\n'% python_path)
            sys.stdout.write('\nSelected Python version is %s\n' % version)
            cmd = data.get('cmd')
            call(cmd)


else:
    from Scripts.my_scriptv3 import *
    Configuration()
const StContainer = document.querySelector('#st-container')

StContainer.onclick = e=>
  {
  if (e.target.className!='click') return

  console.log(e.target.textContent, e.target.dataset.effect)

  let STmenu = document.getElementById(e.target.textContent.toLowerCase())

  STmenu.classList.toggle(e.target.dataset.effect)
  STmenu.classList.toggle('st-menu-open');
  }
.ui {
  background: #215DD1;
  color: #fff;
}

.cv {
  background: #FF9F2F;
  color: #fff;
}

.st-container {
	position: relative;
	overflow: hidden;
}

.st-menu {
	position: absolute;
	top: 0;
	left: 0;
	z-index: 100;
	visibility: hidden;
	width: 300px;
	height: 100%;
	-webkit-transition: all 0.5s;
	transition: all 0.5s;
}

.st-effect-1.st-menu {
	visibility: visible;
	-webkit-transform: translate3d(-100%, 0, 0);
	transform: translate3d(-100%, 0, 0);
}

.st-effect-1.st-menu-open .st-effect-1.st-menu {
	visibility: visible;
	-webkit-transform: translate3d(0, 0, 0);
	transform: translate3d(0, 0, 0);
}

.st-effect-1.st-menu::after {
	display: none;
}

body {
	background: #444;
	color: #48a770;
}