Trajectory planning is an important stage in robot operation. Many imitation learning methods have been researched for learning operation skills from demonstrated trajectories. However, it is still a challenge to use the learned skill models to generate motion trajectories suitable for various changing conditions. In this paper, a closed-loop dynamical evaluation and optimization mechanism is proposed for imitation learning model to generate the optimal trajectories that can adapt to multiple conditions. This mechanism works by integrating the following parts: (1) imitation learning based on an improved dynamic motion primitive; (2) constructing the trajectory similarity evaluation function; (3) presenting an enhanced whale optimization algorithm(EWOA) by introducing the piecewise decay rate and inertia weight for avoiding getting stuck in local optima. The EWOA iteratively optimizes the key parameter of the skill learning model based on the cost function of the trajectory similarity evaluation for generating the trajectory with the highest similarity to the teaching trajectory. The effectiveness of the EWOA is validated using 10 functions by comparing with the other two methods. And the feasibility of the dynamical optimization mechanism is proved under different motion primitives and various generation conditions.