PORTSMOUTH, N.H. — Donald J. Trump is locked in an explosive feud with Republicans in Washington and has already faced humiliating defections within his own party that have destabilized his campaign on the national level.

But closer to the ground, he has also risked alienating an even more pivotal constituency in the swing states that will decide the presidential election: military communities dismayed by his crude and at times offensive comments about the armed services.

Starting last week when he clashed with Khizr and Ghazala Khan, the parents of a Muslim captain in the Army who was killed in Iraq, Mr. Trump has reignited a set of controversies surrounding his approach to the military. He has drawn fresh attention to his derisive comments about Senator John McCain’s capture in Vietnam, as well as to his own avoidance of military service during the same war. He attacked Gen. John R. Allen, a retired Marine who endorsed Hillary Clinton, as a “failed general” over the weekend, and he joked at a campaign event on Tuesday about receiving a Purple Heart, the military decoration for soldiers wounded in combat.