为什么是e.preventDefault();只工作一次?

时间:2017-09-04 20:20:20

标签: javascript

我有一个使用e.preventDefault来阻止它刷新的表单,但是如果我使用该表单再次提交内容,页面会刷新...我已经看过为什么会发生这种情况,但我可以弄清楚为什么它第一次工作但不是第二次......或者第三次......等等......

我已在下面附上我的代码。提前谢谢。

// scripts

// store element in dom
const searchButton = document.getElementById("submit-button");

// add event listener to button
searchButton.addEventListener("click", searchForNews);

// function to search for news
function searchForNews(e) {

	e.preventDefault();

    // store element in dom
    const searchForm = document.getElementById("search-form");

    // retrieve the value in the input field
    const searchTerm = searchForm.value;

    // log to console
    console.log("You searched for " + searchTerm);

    // token
    const token = XXXXXXXX;

    const urlArray = new Array;

    // create the urls to search for the news
    const guardianUrl = "http://webhose.io/filterWebContent?token=" + token + "&format=json&sort=crawled&q=" + searchTerm + "%20site_type%3Anews%20site%3Atheguardian.com%20language%3Aenglish%20performance_score%3A%3E5";
    const bbcUrl = "http://webhose.io/filterWebContent?token=" + token + "&format=json&sort=crawled&q=" + searchTerm + "%20site_type%3Anews%20site%3Abbc.co.uk%20language%3Aenglish%20performance_score%3A%3E5";
    const telegraphUrl = "http://webhose.io/filterWebContent?token=" + token + "&format=json&sort=crawled&q=" + searchTerm + "%20site_type%3Anews%20site%3Atelegraph.co.uk%20language%3Aenglish%20performance_score%3A%3E5";

    // push each url in to the array
    urlArray.push(guardianUrl);
    urlArray.push(bbcUrl);
    urlArray.push(telegraphUrl);

    console.log(urlArray[0])

    // declare element
    const headerWrapper = document.getElementById("header-wrapper");

    // add class to headerWrapper
    headerWrapper.classList.add("header-small");

    // templates for news sources
    guardianTemplate = "<div id='theguardian'data-source='theguardian.com' class='news-wrapper'><div class='source-name'><p>The Guardian</p></div></div>";
    bbcTemplate = "<div id='bbc'data-source='bbc.co.uk' class='news-wrapper'><div class='source-name'><p>BBC News</p></div></div>";
    telegraphTemplate = "<div id='telegraph' data-source='telegraph.co.uk' class='news-wrapper'><div class='source-name'><p>The Telegraph</p></div></div>";

    var articleWrapper = document.getElementById("article-wrapper");

    articleWrapper.innerHTML = "";

    const searchedTemplate = '<div class="searched-for"><h1>You searched for "' + searchTerm + '"</h1></div>';

    // insert template in to header wrapper element 
    headerWrapper.innerHTML += searchedTemplate;

    // insert templates in to element
    articleWrapper.innerHTML += guardianTemplate;
    articleWrapper.innerHTML += bbcTemplate;
    articleWrapper.innerHTML += telegraphTemplate;

    // for loop to go through the url array
    for (let i = 0; i < urlArray.length; i++) {

        // declare a new request
        const newsReq = new XMLHttpRequest();

        // open the request
        newsReq.open('GET', urlArray[i], true);

        // function to run when loading
        newsReq.onload = function() {

            // if the status is between 200 and 399
            if (this.status >= 200 && this.status < 400) {

                // request is successful
                // parse the response
                const res = JSON.parse(this.response);

                // enter the posts object
                const posts = res.posts;

                // for look to go through the response
                for (let i = 0; i < posts.length; i++) {

                    // get the name of the site
                    const source = posts[i].thread.site;

                    // get image
                    const image = posts[i].thread.main_image;

                    // get the title post
                    var title = posts[i].title;

                    // split using the | symbol, take the first string in array
                    var title = title.split("|")[0];

                    // take the string and replace "= BBC News" with nothing
                    var title = title.replace("- BBC News", "");

                    // trim excess spaces around string
                    var title = title.trim();

                    const articleUrl = posts[i].thread.url

                    // log to console
                    console.log(title + " | " + source + " | " + articleUrl);

                    var template = '<a class="link" href="' + articleUrl + '"><div class="article">' + 
                    	'<img class="image" src="' + image + '">' + 
                    	'<div class="title">' + title + '</div>' +
	                    '</div></a>';

                    // declare element
                    var newsWrapper = document.querySelectorAll(".news-wrapper");

                    // look through the newsWrapper element to find elements that match source names
                    var currentWrapper = [...newsWrapper].find((wrapper) => wrapper.dataset.source === source);

                    // create fragment
                    var articleFragment = document.createRange().createContextualFragment(template);

                    // add the fragment to the correct wrapper
                    currentWrapper.appendChild(articleFragment);
                }

            } else {
                // We reached our target server, but it returned an error

            }
        };

        newsReq.onerror = function() {
            // There was a connection error of some sort
        };

        newsReq.send();
    }
}
/* stylesheet */


body {
	font-style: normal;
	font-weight: 600;
	font-size: 18px;
	color: #242424;
}

input {
	font-family: "Graphik";
}

* {
	box-sizing: border-box;
	font-family: "Graphik";
}

.header-wrapper {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 100vw;
	height: 100vh;
	transition: height 0.5s ease;
}

.header-small {
	height: 300px;
}

.logo-wrapper {
	width: 100%;
	max-width: 500px;
	margin-bottom: 25px;
}

.logo {
	max-width: 100%;
}

.search-wrapper {
	width: 100%;
	max-width: 500px;
}

.form-wrapper {
	display: flex;
	flex-direction: row;
	position: relative;
	width: 100%;
	max-width: 500px;
}

.search-form {
	width: 100%;
	text-align: center;
	padding: 10px;
	border-radius: 50px 0 0 50px;
	outline: none;
	border: 1px solid lightgrey;
	border-right: none;
}

.submit-button {
	border-radius: 0 50px 50px 0;
	border: 1px solid lightgrey;
	border-left: none;
	background-color: #FFF;
	padding: 10px;
	width: 45px;
	height: 43px;
	background-image: url(/assets/images/search.svg);
	background-position: center;
	background-repeat: no-repeat;
	background-size: 20px;
	transition: 0.25s ease;
}

.submit-button:hover {
	cursor: pointer;
	background-size: 25px;
}

.article-wrapper {
	display: flex;
	flex-direction: row;
}

.news-wrapper {
	width: 33.33%;
	margin-left: 20px;
	margin-right: 20px;
}

.source-name {
	width: 100%;
	text-align: center;
}

.image {
	max-width: 100%;
}

.article {
	margin-bottom: 20px;
}

.title {
	padding: 10px;
}

.link {
	text-decoration: none;
	color: #242424;
}

@media screen and (max-width: 512px) {

	.header-wrapper {
		padding: 40px;
	}

	.article-wrapper {
		flex-direction: column;
	}

	.news-wrapper {
		width: 100%;
	}

}
<!DOCTYPE html>
<html lang="en">

	<head>

		<!-- character encoding -->
		<meta charset="utf-8">

		<!-- viewport -->
		<meta name="viewport" content="width=device-width,initial-scale=1">

		<!-- optional

		<meta name="author" content="name">
	 	<meta name="description" content="description here">
	  	<meta name="keywords" content="keywords,here">

		-->

		<!-- title of page -->
		<title>BroadBulletin</title>

		<link rel="stylesheet" href="css/style.css" type="text/css">
		<link rel="stylesheet" href="css/normalize.css" type="text/css">
    	
    	<!-- web fonts -->
     	<!-- <link rel="stylesheet" href="css/fonts.css" type="text/css"> -->

	</head>

	<body>

		<div id="header-wrapper" class="header-wrapper">

			<div class="logo-wrapper">

				<img class="logo" src="assets/images/logo.png" alt="logo">

			</div>

			<div class="search-wrapper">

			<div class="form-wrapper">
				
				<form class="form-wrapper">

					<input id="search-form" class="search-form" type="text" placeholder="What's in the news today?">
					<input id="submit-button" class="submit-button" type="submit" value="">

				</form>

			</div>

		</div>

		</div>

		<div class="article-wrapper" id="article-wrapper">

		
			


		</div>

		













		<!-- scripts -->
		<script src="js/script.js" type="text/javascript"></script>

	</body>

</html>

2 个答案:

答案 0 :(得分:1)

尝试处理submit event而不是click

答案 1 :(得分:0)

  • 首先:你不需要一个“提交”按钮,而是一个带有“按钮”类型的按钮(你不再需要preventDefault())。
  • 其次:此行( headerWrapper.innerHTML + = searchingTemplate; )将替换您的搜索dom并删除所有侦听器。对这些信息也使用其他包装。