user id
to input boxget user posts button
that userid
should be retrieved from input text box in order to be displayed in browsers's console.log()
Actual Resulst on browser console.log() id is printed before i click the button
*** Codes***
//click handler to get clicked user id
const getUserPosts = (id) =>{
console.log(id)
}
//getData('users') has a list of ten users
getData('users').then(data=>data.forEach(({name, email, id})=>{
var div = newTag('div')
document.getElementsByClassName('user')[0].appendChild(div);
let listName = newTag('h2')
let listEmail = newTag('p')
let userPostBtn = newTag('button')
let input = newTag('input')
// userPostBtn.setAttribute('onclick', e=>getUserPosts())
userPostBtn.innerHTML = 'Get User’s Posts'
input.setAttribute('name', 'data')
div.appendChild(listName)
div.appendChild(listEmail)
div.appendChild(userPostBtn)
div.appendChild(input)
listEmail.innerHTML = email
listName.innerHTML=name
input.value = id
}))
Try this and let me know
const getUserPosts = (id) =>{ console.log(id) } function newTag(tagName) { return document.createElement(tagName); } function getData() { fetch('https://jsonplaceholder.typicode.com/users', {method: 'get'}). then(data => data.json()). then(data => { console.log(data) data.forEach(({name, email, id})=>{ var div = newTag('div') document.getElementsByClassName('user')[0].appendChild(div); let listName = newTag('h2') let listEmail = newTag('p') let userPostBtn = newTag('button') let input = newTag('input') userPostBtn.innerHTML = 'Get User's Posts' userPostBtn.addEventListener('click', function(e) { getUserPosts(id) }) input.setAttribute('name', 'data') div.appendChild(listName) div.appendChild(listEmail) div.appendChild(userPostBtn) div.appendChild(input) listEmail.innerHTML = email listName.innerHTML=name input.value = id })}).catch(e => { console.log(e) }) } getData()
<div class="user"></div>
If you give your input an id at the time of creation (id could be anything as long as its unique): input.id = 'inputfieldid';
then you can get the value from the input in the event listener
const getUserPosts = (id) =>{ const input = document.getElementById('inputfieldid'); console.log(input.value); }
尝试将onclick
事件更改为如下所示:
userPostBtn.onclick = (e)=>getUserPosts();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.