简体   繁体   中英

How can I extract part of an element, and reuse this (numerical) value in javascript

Ok, so the background to what I would like to do overall is 'randomly select a car from the list of results'.

So far, what I've successfully done is randomly select a Car type from a simple list of possibilities.

var cartype = ['small-city', 'hatchback', 'saloon', 'estate', '4x4']
var selectedtype = cartype[Math.floor(Math.random() * cartype.length)]

What I'm also able to do is randomly select a resulting page from a static value (in this case, any page between 1 and 10);

var cfspageNumber = Math.floor(Math.random() * 11) + 1

I can then load the random page and it all works Ok

.url(`https://www.parkers.co.uk/cars-for-sale/type-${selectedtype}/?page=${cfspageNumber}`)

Upon loading the landing page of the resulting list of cars for sale with the (randomly) selected Car type, what I'd then like to do is randomly select a page so that (in theory) a different list of cars is displayed each time the test is run.

So, in the case below, I would like to randomly select any of the 1882 pages and load that page.

在此处输入图片说明

If the number of pages was always 1882, I'd be Ok as I can randomly select from a 'static' list.

However, depending on what Car type is randomly selected beforehand, the number of pages changes.

What I would like to do, is somehow 'extract' this value (in this case 1882 but is dynamic), and then use this value to randomly select a page.

var cfspageNumber = Math.floor(Math.random() * 1882, or whatever is listed as the final page) + 1

尝试获取a元素并使用.innerHTML

var extractedString = document.querySelector(".results-paging__pages__number a").innerHTML;
var numberOfPages = parseInt(extractedString);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM