The story
Probably a calque of French jeter son bonnet par-dessus les moulins . Widely reported as deriving from a passage in the novel Don Quixote in which the titular character throws his cap over a windmill that he has mistaken for a giant, as a challenge. However, no such passage exists in the book.
Etymology from Wiktionary, CC BY-SA 4.0.