我有button
元素的列表,我希望在单击时为每个元素添加一个类,并从所有其他按钮中删除该类。我怎么能用纯Javascript做到这一点?
<button>btn1</button>
<button>btn2</button>
<button>btn3</button>
<button>btn4</button>
<button>btn5</button>
var el = document.querySelectorAll("button");
el.addEventListener("click", function() {
el.classList.remove("toggle");
this.classList.add("toggle");
});
答案 0 :(得分:1)
两次浏览按钮列表。第一次将事件监听器添加到每个按钮。第二次按下点击。
SCRIPT_NAME="$1"
CURRENT_DATE=`date +%Y-%m-%d`
C_INFO=0
C_SUCCESS=1
C_DEBUG=2
C_WARN=3
C_ERROR=4
LOG_STATUS=(INFO SUCCESS DEBUG WARN ERROR)
function fnCreateLogFile(){
fnGetScriptPath $1
FILE=`basename $1`
LOGDIR=$root_dir/logs
LOGFILE=${LOGDIR}/${FILE/'.sh'/''}_${CURRENT_DATE}.log
if [[ ! -d $LOGDIR ]]; then
mkdir -p $LOGDIR
fnLog "Creating log dir: $LOGDIR" $C_SUCCESS
else
fnLog "Log file : $(cd `dirname $LOGFILE` && pwd)/$FILENAME" "$C_INFO"
fi
}
function fnGetScriptPath(){
script_name=`basename $1`
script_base_name=`echo $script_name | cut -d'.' -f1`
dir_name=`dirname $1`
if [[ $dir_name == "." ]];then
work_dir=`pwd`
root_dir=`pwd | awk 'BEGIN{FS="/"; OFS = "/"} {$NF="";print}' | sed 's/.$//'`
else
work_dir=$dir_name
root_dir=`echo $dir_name | awk 'BEGIN{FS="/"; OFS = "/"} {$NF="";print}' | sed 's/.$//'`
fi
}
function fnLog() {
echo `date +"%Y-%m-%d %k:%M:%S"` $1
echo `date +"%Y-%m-%d %k:%M:%S"` $1 >> $LOGFILE
if [[ $2 -eq 1 || $2 -eq 2 ]]; then MSG_ACCUM="$MSG_ACCUM \\n $1" ;fi
}
function fnGetDate(){
HDFS_SRC=$1
HDFS_TGT=$2
SKIP=${3:-"0"}
for X in ${!HDFS_SRC[*]}
do
#echo "comm -23 <(hadoop fs -ls ${HDFS_SRC[X] } | awk -F'/' '{match(\$NF, \"[0-9]+-[0-9]+-[0-9]+\", v)}{print v[0]}' | sort) <( hadoop fs -ls $HDFS_TGT | awk -F'/' '{match(\$NF, \"[0-9]+-[0-9]+-[0-9]+\", v)}{print v[0]}'"
HDFS=("${HDFS[@]}" "`comm -23 <(hadoop fs -ls ${HDFS_SRC[X] } | awk -F'/' '{match($NF, "[0-9]+-[0-9]+-[0-9]+", v)}{print v[0]}' | sort) <( hadoop fs -ls $HDFS_TGT | awk -F'/' '{match($NF, "[0-9]+-[0-9]+-[0-9]+", v)}{print v[0]}' | sort ) | grep "^[0-9]"`")
done
if [[ $value == "" ]];then
DATE=( $(
for x in "${HDFS[@]}"
do
echo "$x"
done | sort | uniq) )
echo ${DATE[$SKIP]}
else
DATE=( $(
for f in ${HDFS[@]}
do
if [[ "$f" > "$value" || "$f" == "$value" ]];then
echo "$f"
fi
done | sort | uniq) )
echo "${DATE[$SKIP]}"
fi
}
var btns = document.querySelectorAll("button");
var cN = "toggle";
function change(el, cN) {
[].forEach.call(btns, function(btn) {
if (btn.className === cN) {
btn.classList.remove(cN);
}
});
el.classList.add(cN);
}
[].forEach.call(btns, function(btn) {
btn.addEventListener("click", function() {
change(this, cN);
});
});
button {
outline: none;
}
.toggle {
color: orange;
}