在javascript中获得点击的元素?

时间:2015-07-09 08:20:36

标签: javascript

我想添加类来点击li并删除其他li类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PauseThreads {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();

for(int i=0;i<10;i++){
    exec.submit(new Workers());
}


ScheduledExecutorService schedule = (ScheduledExecutorService) Executors.newSingleThreadExecutor();
schedule.scheduleAtFixedRate( new Runnable(){

    @Override
    public void run() {
        Runtime runtime = Runtime.getRuntime();


        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();

        if( (allocatedMemory / maxMemory ) > 0.9 ){
            //pause all the threads running under the exec
        }

    }

},  0, 60, TimeUnit.SECONDS);
}
}

class Workers implements Runnable{

@Override
public void run() {

    // do some work

}

}

我可以用jquery做到但现在我想用javascript做这个吗?

2 个答案:

答案 0 :(得分:2)

不要使用内联点击处理程序。而是从JavaScript附加处理程序。

 <ul id="myUL"> <!-- This is just for example, to make it easier to select -->
    <li><span>خانه</span></li>
    <li><span>سفارش</span></li>
    <li class="selected"><span>آپلود</span></li>
    <li><span>درباره ما</span></li>
    <li><span>تنظیمات</span></li>
 </ul>

然后,在JavaScript中:

var myUL = document.querySelector('#myUL');
// Attach one event listener on the parent, instead of one for each element.
// It's more performant and will work with dynamically added entries!
myUL.addEventListener('click', function(event) {
    // Here, event.target is the actual event clicked.
    // Remove class from selected one.
    document.querySelector('#myUL .selected').classList.remove('selected');
    // And add it to the current one
    event.target.classList.add('selected');
});

<强> Working Example

答案 1 :(得分:1)

这是快速修复,建议不要这样做。但在您的情况下,您需要使用这种方式:

function s (which) {
    document.querySelectorAll(".clicked")[0].classList.remove("selected");
    which.classList.add("selected");
}

以这种方式改变电话:

 <ul>
    <li onclick="s(this)"><span>خانه</span></li>
    <li onclick="s(this)"><span>سفارش</span></li>
    <li onclick="s(this)" class="selected"><span>آپلود</span></li>
    <li onclick="s(this)"><span>درباره ما</span></li>
    <li onclick="s(this)"><span>تنظیمات</span></li>
 </ul>

正确的方法是使用eventListeners并将事件绑定到ID。

var list = document.querySelector('#menu');
list.addEventListener('click', function(event) {
    list.querySelector('.selected').classList.remove('selected');
    event.target.classList.add('selected');
});

并将ID添加到<ul>

<ul id="menu">
    <li>خانه</li>
    <li>سفارش</li>
    <li class="selected">آپلود</li>
    <li>درباره ما</li>
    <li>تنظیمات</li>
 </ul>